Python Regex - Reject strings with newline

后端 未结 2 808
面向向阳花
面向向阳花 2021-01-21 00:52

I want to match complete strings to a specific pattern. Let\'s say :

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

Ho

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-21 01:29

    Instead of anchors ^ and $ use \A for start and \Z for end:

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

    \A matches the actual start of string and \Z the actual end and there can be only one of \A and \Z in a multiline string, whereas $ may be matched in each line.

    I suggest reading this very good article on permanent line anchors.

    Just fyi unlike .NET, Java, PCRE, Delphi, PHP in Python \Z matches only at the very end of the string. Python does not support \z.

提交回复
热议问题