Python正则表达式换行符匹配

2024-04-26 11:20:23 发布

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

我想匹配一个有字母数字和一些特殊字符的字符串,但不匹配换行符。但是,每当我的字符串有换行符时,它也会匹配换行符。我查看了文档中的一些标志,但没有一个看起来相关

下面是python3.6.2repl中的示例代码

>>> import re
>>> s = "do_not_match\n"
>>> p = re.compile(r"^[a-zA-Z\+\-\/\*\%\_\>\<=]*$")
>>> p.match(s)
<_sre.SRE_Match object; span=(0, 12), match='do_not_match'>

预期的结果是,它不应该匹配,因为我有新行在最后

https://regex101.com/r/qyRw5s/1

我有点搞不清楚我在这里错过了什么


Tags: 字符串代码文档importre示例标志match
1条回答
网友
1楼 · 发布于 2024-04-26 11:20:23

问题是$在新行之前的字符串末尾匹配(如果有的话)

如果不想匹配末尾的换行符,请在正则表达式中使用\Z而不是$

请参阅^{}模块的文档:

'$'
Matches the end of the string or just before the newline at the end of the string,

\Z
Matches only at the end of the string.

相关问题 更多 >