簡體   English   中英

正則表達式匹配除特定給定字符串之外的任何內容(包括空字符串)

[英]Regex to match anything (including the empty string) except a specific given string

我想測試一個字符串是否包含"Kansas"其后是" State"以外的任何內容。

例子:

"I am from Kansas"          true
"Kansas State is great"     false
"Kansas is a state"         true
"Kansas Kansas State"       true
"Kansas State vs Kansas"    true
"I'm from Kansas State"     false
"KansasState"               true

對於PCRE ,我相信答案是這樣的:

'Kansas(?! State)'

但Mysql的REGEXP似乎並不喜歡這樣。

附錄:感謝David M推廣這個問題: 如何將PCRE轉換為POSIX RE?

MySQL沒有前瞻性。 解決方法是進行兩項測試:

WHERE yourcolumn LIKE '%Kansas%'
  AND yourcolumn NOT LIKE '%Kansas State%'

我在這里使用了LIKE而不是RLIKE因為一旦你將它拆分成這樣,就不再需要正則表達式了。 但是,如果由於其他原因仍然需要正則表達式,您仍然可以使用相同的技術。

請注意,這與您要求的“堪薩斯州堪薩斯州”不符。

更新:如果匹配'堪薩斯州堪薩斯州'那么重要,那么你可以使用MySQL支持的這個丑陋的正則表達式:

'Kansas($|[^ ]| ($|[^S])| S($|[^t])| St($|[^a])| Sta($|[^t])| Stat($|[^e]))'

哎呀:我剛注意到Kip已經用一個非常類似於此的解決方案更新了他的評論。

這應該有效,假設在MySQL正則表達式中允許前瞻性斷言。

/Kansas(?! State)/

編輯 :好的,這是非常丑陋的,但它在Perl中適用於我,並且不使用前瞻性斷言:

/Kansas(([^ ]|$)| (([^S]|$)|S(([^t]|$)|t(([^a]|$)|a(([^t]|$)|t([^e]|$))))))/

比大型正則表達式更高效(當然,取決於您的數據和引擎的質量)

WHERE col LIKE '%Kansas%' AND
  (col NOT LIKE '%Kansas State%' OR
  REPLACE(col, 'Kansas State', '') LIKE '%Kansas%')

如果堪薩斯州通常以“堪薩斯州”的形式出現,你可能會發現這更好:

WHERE col LIKE '%Kansas%' AND
  REPLACE(col, 'Kansas State', '') LIKE '%Kansas%'

這具有易於維護的附加優點。 如果堪薩斯很常見且文本字段很大,那么它的效果就不那么好了。 當然,您可以根據自己的數據測試這些數據並告訴我們它們的比較方式。

這很難看,但是你走了:

你可能不需要將正則表達式一直擴展到最后,這取決於你的輸入是否包括“我需要讓這個人在堪薩斯統計中接受手術!”。

mysql> select x,x RLIKE 'Kansas($|[^ ]| ($|[^S])| S($|[^t])| St($|[^a])| Sta($|[^t])| Stat($|[^e]))' AS result from examples;
+------------------------+--------+
| x                      | result |
+------------------------+--------+
| I am from Kansas       |      1 |
| Kansas State is great  |      0 |
| Kansas is a state      |      1 |
| Kansas Kansas State    |      1 |
| Kansas State vs Kansas |      1 |
| I'm from Kansas State  |      0 |
| KansasState            |      1 |
+------------------------+--------+
7 rows in set (0.00 sec)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM