2024-10-01 07:35:08 发布
网友
我试着用regex在文本中找到如下元素:abs=abs,1=1等等。 我这样写的:
opis="Some text abs=abs sfsdvc" wyn=re.search('([\w]*)=\1',opis) print(wyn.group(0))
当我在像这样的网站上尝试这个代码时,我什么也没发现www.regexr.com它工作正常。 我在做什么错事吗?你知道吗
必须将regex指定为原始字符串r'..'
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+。你知道吗
[
]
\w+
必须将regex指定为原始字符串
r'..'
From re documentation
也就是说,如果您不打算使用原始字符串,那么字符串中的所有
\
都必须转义为将正则表达式更改为:
注意,这里并不需要character类,
[
和]
是多余的,如果不想匹配字符串“=”(等号),最好使用\w+
。你知道吗相关问题 更多 >
编程相关推荐