2012-05-23 63 views
2

我可以檢查一個字符串是否等於給定的具有正則表達式的關鍵字。這裏是一個例子:檢查一個字符串是X還是不是X

Regex: /^hello$/ 
String: hello 
Result: matches, as expected 

Regex: /^goodbye$/ 
String: goodbye 
Result: matches, as expected 

Regex: /^bye$/ 
String: bye bye 
Result: does not match, as expected 

我無法實現的是檢查一個字符串是否不等於關鍵字。下面是什麼,我試圖做一些例子:

Regex: ^(?!hello).*$ 
String: bye 
Result: matches, as expected 

Regex: ^(?!hello).*$ 
String: bye bye 
Result: matches, as expected 

Regex: ^(?!hello).*$ 
String: say hello 
Result: matches, as expected 

Regex: ^(?!hello).*$ 
String: hello you 
Result: does not match, but should match because "hello you" is not equal to "hello" 

我想我親近^(?!hello).*$但需要一隻手搭在此。這裏是另一個例子:

Regex: ^(?!fresh\sfruits).*$ 
String: fresh fruits 
Result: does not match, as expected 

Regex: ^(?!fresh\sfruits).*$ 
String: lots of fresh fruits 
Result: matches, as expected 

Regex: ^(?!fresh\sfruits).*$ 
String: fresh fruits, love them. 
Result: does not match, but should match 

謝謝!

+0

爲什麼不使用字符串比較,而不是正則表達式? – nhahtdh

+0

我猜這更多是出於好奇和學習,而不是一種實用的方法。 –

+0

好點,但我正在處理的應用程序需要在正則表達式中定義的規則集。這不是好奇心或學習,這是一個真正的需要:) – matte

回答

5

我們只是失敗的情況下添加到您的表達:

^(hello.+|(?!hello).*)$ 

所以第一位比賽你好,其次是任何保存空字符串。 (我剛完成一個自動機班,不禁想起它是ε:P)。第二位匹配任何不以hello開頭的內容。

這涵蓋了所有可能的情況,我想。

1

^(?!hello$)(降.*

(...固定的回顧後/提前混亂)

+0

對於我在JavaScript中'/(?!^ hello)$ /。test(「hello」)'returns'true'。事實上,它似乎會爲每個字符串返回「true」。 –

+0

'(?!^ hello)$'與'bye'不匹配。如果字符串不等於關鍵字,則正則表達式應匹配。 – matte

+0

阿哈,在我打字的時候走出了門,混合了一些前方/後方。現在修復。 – Wrikken

相關問題