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

前端 未结 3 869
猫巷女王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:35

    You more likely don't need $ but rather \Z:

    >>> print(re.match(r'^foobar\Z', 'foobar\n'))
    None
    
    • \Z matches only at the end of the string.

提交回复
热议问题