如何匹配一个n位数字符串,如果重复一个特定的数字,如果在一起只能重复m次?

问题描述 投票:0回答:3

我有一个10位数的字符串,条件是连续重复的任何数字,只能重复4次,否则重复没有限制

示例:

1234567890 "match"
1213141516 "match"
1111234567 "match"
1233333456 "not match"

我怎么能用正则表达式做到这一点?

python regex
3个回答
2
投票

您可以使用以下正则表达式,并根据是否找到捕获组返回'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'

0
投票

您是否需要使用RegEx执行此操作而不是包含以下内容的简单循环:

/* Code to get current and previous char */
if (currentChar == previousChar) { numRepeats += 1; } else { numRepeats = 0; }
if (numRepeats > 4) { return false }

0
投票

^(?!\d*(\d)\1{4})\d{10}$

在这里看到https://regex101.com/r/LX8zQs/1

© www.soinside.com 2019 - 2024. All rights reserved.