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
348 views
in Technique[技术] by (71.8m points)

php - In a regex, what changes when you add a question mark to .+

I was browsing old php sources and I found a pattern I don't understand (probably a copy/past from the internet some times ago ...).

Here is a simple exemple using it with php :

echo preg_replace('#color="(.+)"#', '$1', 'color="red" color="black"');
// Echo 'red" color="black', which is fine because the (.+) try to match the largest possible string.

echo preg_replace('#color="(.+?)"#', '$1', 'color="red" color="black"');
// Echo 'red black', why ? There is some black magic behind '(.+?)' I don't understand !

So what does the '?' do in '(.+?)' ? I assume it says something like 'don't match the rest of the regex' but I'm looking for a detailed explanation !

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

+ is a greedy operator; consuming as much as possible. Therefore, .+ will match as much as it can and still allow the remainder of the regular expression to match. Once you specify the question mark +?, you're telling the regex engine (don't be greedy.. as soon as you find a double quote "... stop, you're done.)


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

...