regex pattern that matches the string at the end of a string but is not followed by line break

前端 未结 1 432
暖寄归人
暖寄归人 2020-12-20 01:04

I use a regex pattern i preg_match php function. The pattern is let\'s say \'/abc$/\'. It matches both strings:

\'abc\'

and

相关标签:
1条回答
  • 2020-12-20 01:50

    The reason why /abc$/ matches both "abc\n" and "abc" is that $ matches the location at the end of the string, or (even without /m modifier) the position before the newline that is at the end of the string.

    You need the following regex:

    /abc\z/
    

    where \z is the unambiguous very end of the string, or

    /abc$/D
    

    where the /D modifier will make $ behave the same way as \z. See PHP.NET:

    The meaning of dollar can be changed so that it matches only at the very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at compile or matching time.

    See the regex demo

    0 讨论(0)
提交回复
热议问题