是否可以使用正则表达式检测重复的数字模式?
因此,例如,如果我有以下字符串"034503450345",是否可以匹配重复序列0345?我有一种感觉,这超出了正则表达式的范围,但我想我还是会问这里,看看我是否错过了什么.
Pet*_*ton 19
此表达式将匹配一个或多个重复组:
(.+)(?=\1+)
Run Code Online (Sandbox Code Playgroud)
这是相同的表达式,(使用注释,因此它仍然可以直接用作正则表达式).
(?x) # enable regex comment mode
( # start capturing group
.+ # one or more of any character (excludes newlines by default)
) # end capturing group
(?= # begin lookahead
\1+ # match one or more of the first capturing group
) # end lookahead
Run Code Online (Sandbox Code Playgroud)
要匹配特定模式,请更改.+
为该模式,例如\d+
,一个或多个数字,或\d{4,}
匹配4个或更多数字.
为了匹配特定数量的模式,改变\1+
例如\1{4}
四次重复.
为了使重复不会彼此相邻,您可以.*?
在前瞻中添加内容.
是的,你可以 - 这是一个Python测试用例
import re
print re.search(r"(\d+).*\1", "8034503450345").group(1)
# Prints 0345
Run Code Online (Sandbox Code Playgroud)
正则表达式说"找到一些数字序列,然后找到任何数量的其他东西,然后再找到相同的序列."
在几乎没有相关的说明中,这是我最喜欢的正则表达式之一 - 素数检测器:
import re
for i in range(2, 100):
if not re.search(r"^(xx+)\1+$", "x"*i):
print i
Run Code Online (Sandbox Code Playgroud)