2017-08-19 29 views
0

關於這個問題有幾個問題,但他們都沒有讓我找到答案,它們都太具體或太長而且很複雜。礦是更一般和簡單。我有這樣一個規律:正則表達式匹配任何單個單詞或沒有任何內容

/you(?:.*)? see/ 

我希望它所有的這些句子,除了最後一場比賽:

you can see 
you could see 
you see 
you could not see 

在它匹配的一切的時刻,但它也匹配的最後一句話。我需要它只匹配任何一個單詞或沒有單詞。我也嘗試過這種模式,但它並沒有完全奏效:

/you(?:[^\s]+)? see/ 

回答

0

這一個做這項工作:

/^you(?:\s+\w+)?\s+see$/ 

哪裏(?:\s+\w+)?是匹配1個或多個空格後面跟着一個可選的非捕獲組1個或多個字字符(即[a-zA-Z-9_]

在動作:

$strings = array(
'you can see', 
'you could see', 
'you see', 
'you could not see', 
); 

foreach ($strings as $str) { 
    if (preg_match('/^you(?:\s+\w+)?\s+see$/', $str)) { 
     echo "$str : matches\n"; 
    } else { 
     echo "$str : doesn't match\n"; 
    } 
} 

輸出:

you can see : matches 
you could see : matches 
you see : matches 
you could not see : doesn't match 
+0

似乎不工作時,我測試regex101.com – Hasen

+0

@Hasen:不信任的站點。製作一個腳本,看看它給了什麼。看我的編輯。 – Toto

+0

regex101.com不是一些隨機網站,它是檢查正則表達式模式的標準。所有模式都可以工作100%。你的模式仍然不起作用... – Hasen

0

,因爲我解決了它之後不久,但已經有一個迴應,我會刪除的問題。我發現,只有變着花樣這解決了這個問題:

/you(?:\s[^\s]+)? see/ 
+1

請注意,'[^ \ s]'匹配不是空格的所有內容,例如'&#{[|!%...' – Toto

相關問題