1
爲什麼an?|the
無效?我使用PHP的preg_match()。PHP正則表達式:OR含有量詞的語句
這裏是完整的正則表達式:"/^an?|the (.+?) (is|was) an? (.+?)$/"
。
我希望它匹配"the mona lisa is a painting"
和"a dog is an animal"
。
它工作正常,直到我加入|the
以適應第一個字符串示例。
謝謝!
爲什麼an?|the
無效?我使用PHP的preg_match()。PHP正則表達式:OR含有量詞的語句
這裏是完整的正則表達式:"/^an?|the (.+?) (is|was) an? (.+?)$/"
。
我希望它匹配"the mona lisa is a painting"
和"a dog is an animal"
。
它工作正常,直到我加入|the
以適應第一個字符串示例。
謝謝!
你寫的方式,它要麼匹配使用
^an?
或
the (.+?) (is|was) an? (.+?)$
這顯然不是你想要的。你必須把它放在括號你is|was
所採取的方式:
/^(an?|the) (.+?) (is|was) an? (.+?)$/
爲了防止一組被包括在結果中,使用不匹配的組,其語法是(?:)
。所以就這樣使用它:
/^(?:an?|the) (.+?) (is|was) an? (.+?)$/
你是上帝!謝謝。 – JoeRocc
hrmm,我懷疑需要在它周圍有'()'。 – Corbin
啊。但隨後它成爲$ matches數組的一部分 - 這對我來說非常不方便。任何可能的解決方法? – JoeRocc
非存儲括號(專有名稱可以轉義我):'(?:an?| the)' – Corbin