任何人都可以帮我创建一个可以检查数字是否有 2 和 4 个重复数字的正则表达式,例如如何检查这个 no 5555122
。
我想通过正则表达式知道有第四个双倍的重复。
您可以使用反向引用
(\d)\1{3}
这将检查 4 位数字的重复
尝试这个
(\d)(?:\1{3}|\1)
解释
"
( # Match the regular expression below and capture its match into backreference number 1
\\d # Match a single digit 0..9
)
(?: # Match the regular expression below
# Match either the regular expression below (attempting the next alternative only if this one fails)
\\1 # Match the same text as most recently matched by capturing group number 1
{3} # Exactly 3 times
| # Or match regular expression number 2 below (the entire group fails if this one fails to match)
\\1 # Match the same text as most recently matched by capturing group number 1
)
"
编辑
里面的图案(?:\1{3}|\1)
,需要多加注意。如果是这样(?:\1|\1{3})
,它将与预期不符。因为,The Regex-Directed Engine Always Returns the Leftmost Match
。