2014-08-27 43 views
1

我在瀏覽舊的php源代碼,並且發現了一種我不明白的模式(可能是前一次從互聯網複製/過去...) 。在正則表達式中,當你添加一個問號時會發生什麼變化。+

下面是使用它與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 ! 

那麼,是什麼的在'(。+?)'中做? 我假設它說'不匹配正則表達式的其餘部分',但我正在尋找一個詳細的解釋!

+1

'? ''+'強制正則表達式引擎做一個儘可能短的匹配(非貪婪或不情願)。 – 2014-08-27 13:29:22

+0

這是一個不情願的量詞。它尋找匹配'。+'的最小序列。更多信息:http://stackoverflow.com/questions/5319840/greedy-vs-reluctant-vs-possessive-quantifiers – Aserre 2014-08-27 13:31:18

+1

可能的重複[參考 - 這是什麼正則表達式?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – 2014-08-27 13:31:20

回答

1

+greedy算子;儘可能消耗。因此,.+將盡可能地匹配並且仍然允許正則表達式的其餘部分匹配。一旦您指定了問號+?,你告訴正則表達式引擎(不要貪...只要你找到一個雙引號" ...停,你就大功告成了。)

1

?,使比賽非貪婪,這意味着表達.+?將匹配儘可能少的字符可能使正則表達式匹配,而不是任意地,這是默認的行爲匹配。

相關問題