2010-09-23 89 views
4

我試圖構造一個正則表達式,將匹配的模式作爲這樣的正則表達式:需要符合「字詞1,word2和WORD3」

word1, word2, word3 

所以基本上我想「」出現兩次並在他們之間有詞。到目前爲止,我想出了:

$general_content_check = preg_match("/^.*, .*$/", $general_content); 

但這只是「」多次在一個字符串匹配。

有人可以幫我這個嗎?

回答

4

嘗試

"/^\w+, \w+, \w+$/" 
+0

對,謝謝Jens! – Pavel 2010-09-23 09:23:50

7

這取決於你所說的 「字」 的意思,但你可以嘗試這樣開始:

^[^,]+(?:, +[^,]+){2}$ 

說明:

 
^   Start of line/string. 
[^,]+  A "word" (anything that isn't a comma - including whitespace, etc.) 
(?:  Start non-capturing group 
    , + A comma then any number of spaces 
    [^,]+ A word 
)   Close group 
{2}  Repeat group exactly two times 
$   End of line/string. 

其他可能的定義「字「:

  • 任何東西,除了空格或逗號:[^\s,]+
  • 在AZ只有字母:[A-Z]+(選擇性地添加不區分大小寫的標誌)
  • 任何字母在Unicode中的任何語言:\p{L}+(未得到廣泛支持)
  • 等。
+0

代碼的好解釋。對於需要這種解釋的新手程序員非常有幫助。 – matsolof 2010-09-23 10:32:00

相關問題