代码:
import re
r = re.search("?:((xxxx)|(yyyy)|(zzzz))+", "x = y + z")
错误消息:
D:/FILE_MGMT_PYTHON/ghqer4tqaery.py
Traceback (most recent call last):
File "D:/FILE_MGMT_PYTHON/ghqer4tqaery.py", line 4, in <module>
r = re.search("?:((xxxx)|(yyyy)|(zzzz))+", "x = y + z")
File "C:\Users\Sam\AppData\Local\Programs\Python\Python38-32\lib\re.py", line 199, in search
return _compile(pattern, flags).search(string)
File "C:\Users\Sam\AppData\Local\Programs\Python\Python38-32\lib\re.py", line 302, in _compile
p = sre_compile.compile(pattern, flags)
File "C:\Users\Sam\AppData\Local\Programs\Python\Python38-32\lib\sre_compile.py", line 764, in compile
p = sre_parse.parse(p, flags)
File "C:\Users\Sam\AppData\Local\Programs\Python\Python38-32\lib\sre_parse.py", line 948, in parse
p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
File "C:\Users\Sam\AppData\Local\Programs\Python\Python38-32\lib\sre_parse.py", line 443, in _parse_sub
itemsappend(_parse(source, state, verbose, nested + 1,
File "C:\Users\Sam\AppData\Local\Programs\Python\Python38-32\lib\sre_parse.py", line 668, in _parse
raise source.error("nothing to repeat",
re.error: nothing to repeat at position 0
Process finished with exit code 1
答案 0 :(得分:3)
正则表达式以?
元字符开头。 ?
的意思是“前面的事物为零或一遍”。如果将?
放在正则表达式的开头,则由于错误原因,没有任何内容可以重复零次或多次,因此正则表达式无效。
将正则表达式重新排列为(?:(xxxx)|(yyyy)|(zzzz))+
会导致(?:
被解释为我不打算使用的捕获组。
答案 1 :(得分:0)
?
:匹配前置子表达式零次或一次。
这是您想要的吗?
import re
r = re.search("(?:(x))|(?:(y))|(?:(z))+", "x = y + z")
print(r.groups()) # But re.search() will only return the first successful matched result
或找到方程式中的所有变量?像这样:
import re
r = re.findall(" *([xyz])+ *", "x = y + z", re.I)
print(r)