正则表达式匹配不相等或不反转的数字组

2024-01-08

我在这里指的是这个问题的后续:正则表达式匹配两个不相等的数字 https://stackoverflow.com/questions/5257685/regular-expression-to-match-two-numbers-that-are-not-equal

现在我的另一个问题场景是这样的:

P121324 - T  
P1212 - F - we got this covered in the message on link above (no same "sets")
P1221 - F - now new restriction - not even the reversed digits 12 - 21  

但是,现在的问题是P串可能会很长! - 像这样:

P121315162324  

请注意,这是可以的,因为“集合”是:

12 13 14 15 16 23 24  

现在,我可以通过检查是否有重复来在代码(PHP)中做到这一点,但我想知道这是否可以使用单个正则表达式命令来完成?


尝试这个:

^P(?:([0-9])(?!\1)([0-9])(?!(?:..)*(?:\1\2|\2\1)))*$

如果您希望像上一个问题一样将数字限制为 [1-6],请将 [0-9] 更改为 [1-6]。

看看它在线工作:rubular http://www.rubular.com/r/AGlyBYW9KW


以下是正则表达式的细分:



^          Start of string/line.
P          Literal P
(?:<snip>) Non-capturing group that matches a distinct pair of digits. See below.
*          Zero or more pairs (use + if you want to require at least one pair).
$          End of string/line.
  

的解释([0-9])(?!\1)([0-9])(?!(?:..)*(?:\1\2|\2\1))- 匹配一对:



([0-9])    Match and capture the first digit. Later refered to as \1.
(?!\1)     Negative lookahead. The next character must not be the same as \1.
([0-9])    Match and capture a digit. Later refered to as \2.
(?!<snip>) Negative lookahead. Check that the pair doesn't occur again.
  

的解释(?:..)*(?:\1\2|\2\1)- 尝试再次找到同一对:



(?:..)*       Match any number of pairs.
(?:\1\2|\2\1) Match either \1\2 or \2\1.
  
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

正则表达式匹配不相等或不反转的数字组 的相关文章

随机推荐