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

大兔子大兔子 提交于 2019-11-28 05:40:27

问题


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

'abc'

and

'abc
'

The second one has the line break at its end. What would be the pattern that matches only this first string?

'abc'

回答1:


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



来源:https://stackoverflow.com/questions/38190269/regex-pattern-that-matches-the-string-at-the-end-of-a-string-but-is-not-followed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!