2009-12-01 74 views
5

我有正則表達式的問題。 我需要制定正則表達式,除了一組指定的詞,例如:蘋果,橙子,果汁。 並且給出這些詞,它將匹配除了上面的那些詞之外的所有詞。正則表達式,除了特定的詞

apple (should not match) 
applejuice (match) 
yummyjuice (match) 
yummy-apple-juice (match) 
orangeapplejuice (match) 
orange (should not match) 
juice (should not match) 
orange-apple-juice (match) 
apple-orange-aple (match) 
juice-juice-juice (match) 
orange-juice (match) 
+0

你在用什麼語言?也應該「橙汁」相匹配還是失敗? – gnarf 2009-12-01 13:18:14

回答

-1

喜歡的東西(PHP)

$input = "The orange apple gave juice"; 
if(preg_match("your regex for validating") && !preg_match("/apple|orange|juice/", $input)) 
{ 
    // it's ok; 
} 
else 
{ 
    //throw validation error 
} 
+0

除了匹配'applejuice'並因此引發驗證錯誤。 – gnarf 2009-12-01 13:15:30

7

如果你真的想用一個正則表達式來做到這一點,你可能會發現有用的環視(在這個例子中尤其是負面前瞻)。正則表達式的紅寶石(某些實現對lookarounds不同的語法)編寫的:

rx = /^(?!apple$|orange$|juice$)/ 
1

聽起來像是你要正確對待連字符作爲一個單詞字符。

3

我注意到apple-juice應該根據你的參數進行匹配,但是apple juice呢?我假設,如果你正在驗證apple juice你仍然希望它失敗。

所以 - 允許建立的字符集算作一個「邊界」:

/[^-a-z0-9A-Z_]/  // Will match any character that is <NOT> - _ or 
         // between a-z 0-9 A-Z 

/(?:^|[^-a-z0-9A-Z_])/ // Matches the beginning of the string, or one of those 
         // non-word characters. 

/(?:[^-a-z0-9A-Z_]|$)/ // Matches a non-word or the end of string 

/(?:^|[^-a-z0-9A-Z_])(apple|orange|juice)(?:[^-a-z0-9A-Z_]|$)/ 
    // This should >match< apple/orange/juice ONLY when not preceded/followed by another 
    // 'non-word' character just negate the result of the test to obtain your desired 
    // result. 

在大多數正則表達式的口味\b算作一個「單詞邊界」,但「單詞字符」標準列表沒有按」 t包括-,所以你需要創建一個自定義的。它可以配合/\b(apple|orange|juice)\b/如果你不是試圖趕上-,以及...

如果您只是在測試「一個字」測試你可以用更簡單的去:

/^(apple|orange|juice)$/ // and take the negation of this... 
0

這得到一些存在方式:

((?:apple|orange|juice)\S)|(\S(?:apple|orange|juice))|(\S(?:apple|orange|juice)\S) 
0
\A(?!apple\Z|juice\Z|orange\Z).*\Z 

,除非它僅由禁詞之一將匹配整個字符串。

或者,如果你不使用Ruby或您確信您的字符串包含不換行或已設置的選項^$不匹配的行開始/結束

^(?!apple$|juice$|orange$).*$ 

也將工作。