Regular expression syntax for “match nothing”?

前端 未结 6 912
清酒与你
清酒与你 2021-01-31 00:58

I have a python template engine that heavily uses regexp. It uses concatenation like:

re.compile( regexp1 + \"|\" + regexp2 + \"*|\" + regexp3 + \"+\" )
<         


        
6条回答
  •  执念已碎
    2021-01-31 01:50

    To match an empty string - even in multiline mode - you can use \A\Z, so:

    re.compile('\A\Z|\A\Z*|\A\Z+')
    

    The difference is that \A and \Z are start and end of string, whilst ^ and $ these can match start/end of lines, so $^|$^*|$^+ could potentially match a string containing newlines (if the flag is enabled).

    And to fail to match anything (even an empty string), simply attempt to find content before the start of the string, e.g:

    re.compile('.\A|.\A*|.\A+')
    

    Since no characters can come before \A (by definition), this will always fail to match.

提交回复
热议问题