Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 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 Answer

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...