[英]MYSQL Regex Negative Lookahead alternative
我正在對郵政編碼/郵政編碼字段進行查詢。
我一直在做一些研究,不支持負面前瞻:
“MySQL 支持 POSIX 正則表達式,而不是 PCRE”
是否有以下替代解決方案,使用 MYSQL 支持的正則表達式?
(?i)^W(?!C)
-- 這是 PHP 中的解決方案
以及對數據庫的示例查詢
select postcode from `postcodes` WHERE LOWER(postcode) REGEXP '^W(?!C)'
在 MySQL 中,您可以使用
WHERE postcode REGEXP '^W([^C]|$)'
([^C]|$)
匹配除C
或字符串結尾之外的任何字符。 此外,無需使用TOLOWER
因為默認情況下正則表達式搜索不區分大小寫。
查看在線測試:
SELECT 'wc' REGEXP '^W([^C]|$)'; // => 0
SELECT 'wR' REGEXP '^W([^C]|$)'; // => 1
SELECT 'w' REGEXP '^W([^C]|$)'; // => 1
您可以反轉您想要實現的正則表達式並使用NOT REGEXP
SELECT postcode from `postcodes`
WHERE postcode NOT REGEXP '^w(c|$)'
上面的一段代碼是關於問題中詢問的單個字符。 對於在此線程中結束並尋找帶有完整單詞的否定前瞻的人來說,這與@Wiktor Stribiżew 的其他答案形成對比也是可能的
-- So not the word 'not_this_word' or end of the string '$'
SELECT postcode from `postcodes`
WHERE postcode NOT REGEXP '^w(not_this_word|$)'
或者您可以使用 NOT IN 進行子查詢
SELECT postcode from `postcodes`
WHERE postcode NOT IN (
SELECT postcode from `postcodes` WHERE postcode REGEXP '^w(not_this_word|$)'
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.