python中的Regex,重复片段查找

2024-10-01 07:35:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用regex在文本中找到如下元素:abs=abs,1=1等等。 我这样写的:

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

当我在像这样的网站上尝试这个代码时,我什么也没发现www.regexr.com它工作正常。 我在做什么错事吗?你知道吗


Tags: 代码text文本re元素search网站group
2条回答

必须将regex指定为原始字符串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

将正则表达式更改为:

re.search(r'(\w+)=\1', opis).group()
          ↑

注意,这里并不需要character类,[]是多余的,如果不想匹配字符串“=”(等号),最好使用\w+。你知道吗

相关问题 更多 >