[英]How to describe string with only repeated characters groups in regular expression in Python
即'aaeegggwwqqqqq', 'ttteeyyjjj'
我試過r'(([az])\\1*)+$'
,但得到錯誤說:無法引用開放組。
任何人都可以幫我弄清楚嗎? 謝謝!
做
(([a-z])\2*)+$
工作?
快速查找, (([az])\\2*)
是第一組, ([az])
是第二組。 看起來您打算引用第二組。
您應該使用非捕獲外部組:
re.match(r'(?:([a-z])\1+)+$', s)
查看正則表達式演示
這樣,您不必重新調整模式內的反向引用。
另一種方法是使用命名的捕獲組和命名的反向引用:
re.match(r'((?P<l>[a-z])(?P=l)+)+$', s)
在這里, (?P<l>[az])
將一個 ASCII 小寫字母捕獲到組“l”中,並且(?P=l)+
匹配 1 個或多個( +
匹配一個或多個量化子模式的出現次數盡可能多) 捕獲的信件的出現。
import re
s = ["aaeegggwwqqqqq", "ttteeyyjjj", "sdfghj"]
for x in s:
if re.match(r'(?:([a-z])\1+)+$', x):
print("{0} matches the pattern".format(x))
輸出:
aaeegggwwqqqqq matches the pattern
ttteeyyjjj matches the pattern
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.