Regex: don't match string ending with newline (\n) with end-of-line anchor ($)

前端 未结 3 842
猫巷女王i
猫巷女王i 2021-01-05 13:00

I can\'t figure out how to match a string but not if it has a trailing newline character (\\n), which seems automatically stripped:

import re

p         


        
3条回答
  •  不知归路
    2021-01-05 13:41

    This is the defined behavior of $, as can be read in the docs that @zvone linked to or even on https://regex101.com:

    $ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)

    You can use an explicit negative lookahead to counter this behavior:

    import re
    
    print(re.match(r'^foobar(?!\n)$', 'foobar'))
    # <_sre.SRE_Match object; span=(0, 6), match='foobar'>
    
    print(re.match(r'^foobar(?!\n)$', 'foobar\n'))
    # None
    
    print(re.match(r'^foobar(?!\n)$', 'foobar\n\n'))
    # None
    

提交回复
热议问题