问题描述
我正在寻找一个正则表达式来匹配重复的数字序列。数字/范围本身可以是任何三位数字,例如我要匹配
345
346-348
234,235,236,237-239
234,234,236 and 237-239
234,236 or 237-239
我不想匹配
3454
111-222-333
454,4567 (match only 454)
该号码可以是任何三位数字。我在混合中尝试了不同的正则表达式 \d{3},但我没有找到任何有效的方法。感谢您对此的任何帮助。
解决方法
你可以使用这个正则表达式:
^\d{3}(?:-\d{3})?(?:\s*(?:,|and|or)\s*\d{3}(?:-\d{3})?)*(?=,|$)
正则表达式详情:
-
^
:开始 -
\d{3}
:匹配 3 个数字 -
(?:-\d{3})?
:可选后跟一个连字符和 3 个数字 -
(?:
:启动非捕获组-
\s*
:匹配 0 个或多个空格 -
(?:,|and|or)
:匹配逗号或and
或or
-
\s*
:匹配 0 个或多个空格 -
\d{3}
:匹配 3 个数字 -
(?:-\d{3})?
:可选后跟一个连字符和 3 个数字
-
-
)*
:启动非捕获组。重复此组 0 次或更多次 -
(?=,|$)
:先行以断言当前位置前面有一个逗号或行尾
根据您展示的样品,您可以尝试以下操作吗?
^\d{3}(?:-\d{3}$|(?:(?:,\s*\d{3}\s*){1,3}-\d{3})|(?:,\d{3},\s*\d{3}\s*(?:and|or)\s*\d{3}-\d{3})?)*(?=,|$)
说明:为以上添加详细说明。
^\d{3} ##Checking from starting of value if value starts from 3 digits.
(?: ##Creating 1st capturing group here.
-\d{3}$| ##Matching - followed by 3 digits at end of value OR.
(?: ##Creating 2nd capturing group here.
(?:,3} ##In a non-capturing group matching,\s* followed by 3 digits with \s* and this whole group 3 times.
-\d{3} ##Followed by - 3 digits.
)| ##Closing 2nd capturing group OR.
(?: ##Creating 3rd capturing group here.,\s*\d{3}\s* ##Matching,3 digits,\s* 3 digits \s*
(?:and|or) ##Matching and OR or strings in a non-capturing group here.
\s*\d{3}-\d{3} ##Matching \s* followed by 3 digits-3digits
)? ##Closing 3rd capturing group keeping it optional.
) ##Closing 1st capturing group here.
*(?=,|$) ##nd matching its 0 or more matches followed by comma OR end of line.