我可以檢查一個字符串是否等於給定的具有正則表達式的關鍵字。這裏是一個例子:檢查一個字符串是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
謝謝!
爲什麼不使用字符串比較,而不是正則表達式? – nhahtdh
我猜這更多是出於好奇和學習,而不是一種實用的方法。 –
好點,但我正在處理的應用程序需要在正則表達式中定義的規則集。這不是好奇心或學習,這是一個真正的需要:) – matte