Skip to main content
 首页 » 编程设计

python之python中的正则表达式,重复片段查找

2024年08月26日30hnrainll

我尝试使用正则表达式在文本中查找如下元素:abs=abs、1=1 等。 我是这样写的:

opis="Some text abs=abs sfsdvc" 
wyn=re.search('([\w]*)=\1',opis) 
print(wyn.group(0)) 

这什么也没找到,当我在 www.regexr.com 等网站上尝试这段代码时,它工作正常。 我在 python re 中做错了什么吗?

请您参考如下方法:

您必须将正则表达式指定为原始字符串 r'..'

>>> opis="Some text abs=abs sfsdvc" 
>>> wyn=re.search(r'([\w]*)=\1',opis) 
>>> print wyn.group(0) 
abs=abs 

From re documentation

Raw string notation (r"text") keeps regular expressions sane. Without it, every backslash ('\') in a regular expression would have to be prefixed with another one to escape it. For example, the two following lines of code are functionally identical:

意思是,如果您不打算使用原始字符串,那么字符串中的所有 \ 都必须转义为

>>> opis="Some text abs=abs sfsdvc" 
>>> wyn=re.search('([\\w]*)=\\1',opis) 
>>> print wyn.group(0) 
abs=abs