【问题标题】:Python Regex - Reject strings with newlinePython Regex - 用换行符拒绝字符串
【发布时间】:2016-04-18 14:30:11
【问题描述】:

我想将完整的字符串匹配到特定的模式。比方说:

word = "aaaa"
test = re.match(r"^aaaa$", word) # this returns True

但是,如果单词后跟换行符:

word = "aaaa\n"
test = re.match(r"^aaaa$", word) # Also returns True :(

但我想找到一种方法让它在最后一种情况下返回 False。有没有办法区分“\n”?

【问题讨论】:

  • 有简单的方法,但^aaaa(?=(?!\n)$) 会工作

标签: python regex newline


【解决方案1】:

使用\A 代替锚点^$ 开始,\Z 结束:

>>> print re.match(r'\Aaaaa\Z', 'aaaa')
<_sre.SRE_Match object at 0x1014b9bf8>

>>> print re.match(r'\Aaaaa\Z', 'aaaa\n')
None

\A 匹配字符串的实际开头,\Z 实际结尾,并且在多行字符串中只能有\A\Z 之一,而$ 可以在每一行中匹配。

我建议reading this very good article on permanent line anchors.

仅供参考,与Python中的Python中的.NETJavaPCREDelphiPHP不同,\Z仅匹配字符串的最末尾。 Python 不支持\z

【讨论】:

  • 太棒了。不知道我怎么错过了!非常感谢。
【解决方案2】:

您可以使用negative lookaheads 来检查它是否包含换行符。在您的情况下,^aaaa(?!\n)$

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    相关资源
    最近更新 更多