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

时间:2011-03-10 10:37:23

标签: regex

我在这里提到这个问题的后续跟进: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)中进行此操作,但我想知道是否可以使用单个正则表达式命令完成此操作?

1 个答案:

答案 0 :(得分:3)

试试这个:

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

如果您希望将数字限制为[1-6],请将[0-9]更改为[1-6]。

查看在线工作:rubular


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

^          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.