Python 正则表达式换行转义字符



我对Python的正则表达式有点困惑。具体来说,为什么以下行不返回True

代码:bool(re.search(r'abn^c$', 'abnc'))

$匹配字符串的末尾,因此c必须位于末尾。但是,匹配的字符串以c$结尾。接下来,您还包含^,它与字符串的开头匹配,但将其放在表达式的中间。

转义^$,以便它们与文本匹配,或者^文本中每行的开头与re.MULTILINE标志匹配,并从文本中删除^$以匹配。

演示:

>>> import re
>>> bool(re.search(r'abn^c$', 'abn^c$'))  # escaped
True
>>> # multiline and target text adjusted
...
>>> bool(re.search(r'abn^c$', 'abnc', flags=re.MULTILINE)) 
True

最新更新