Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

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

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'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason why /abc$/ matches both "abc " 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:

/abcz/

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...