我有一个10位数的字符串,条件是连续重复的任何数字,只能重复4次,否则重复没有限制
示例:
1234567890 "match"
1213141516 "match"
1111234567 "match"
1233333456 "not match"
我怎么能用正则表达式做到这一点?
您可以使用以下正则表达式,并根据是否找到捕获组返回'match'
或'not_match'
。
\1
将指定您希望{4}
重复第一个捕获组:
def valid_string(s, lim=10):
m = re.search(r'(\d)\1{4}', s)
return 'match' if not m and len(s)==lim else 'not_match'
valid_string('1234567890')
# 'match'
valid_string('1111234567')
# 'match'
valid_string('1233333456')
# 'not_match'
您是否需要使用RegEx执行此操作而不是包含以下内容的简单循环:
/* Code to get current and previous char */
if (currentChar == previousChar) { numRepeats += 1; } else { numRepeats = 0; }
if (numRepeats > 4) { return false }
^(?!\d*(\d)\1{4})\d{10}$