简体   繁体   English

MYSQL 正则表达式负前瞻替代方案

[英]MYSQL Regex Negative Lookahead alternative

I'm doing a query on a postcode/zip code field.我正在对邮政编码/邮政编码字段进行查询。
I've been doing a bit of research and negative lookaheads aren't supported:我一直在做一些研究,不支持负面前瞻:

"MySQL supports POSIX regular expressions, not PCRE" “MySQL 支持 POSIX 正则表达式,而不是 PCRE”

Is there an alternative solution to the below, using the regular expressions supported by MYSQL?是否有以下替代解决方案,使用 MYSQL 支持的正则表达式?

(?i)^W(?!C) -- this is the solution in PHP (?i)^W(?!C) -- 这是 PHP 中的解决方案

And an example query to the database以及对数据库的示例查询

select postcode from `postcodes` WHERE LOWER(postcode) REGEXP '^W(?!C)'

In MySQL, you may use在 MySQL 中,您可以使用

WHERE postcode REGEXP '^W([^C]|$)'

([^C]|$) matches any char but C or end of string. ([^C]|$)匹配除C或字符串结尾之外的任何字符。 Also, no need to use TOLOWER as the regex search is case insensitive by default.此外,无需使用TOLOWER因为默认情况下正则表达式搜索不区分大小写。

See the online tests :查看在线测试

SELECT 'wc' REGEXP '^W([^C]|$)'; // => 0
SELECT 'wR' REGEXP '^W([^C]|$)'; // => 1
SELECT 'w' REGEXP '^W([^C]|$)';  // => 1

You can inverse the regex of what you want to achieve and use NOT REGEXP您可以反转您想要实现的正则表达式并使用NOT REGEXP

SELECT postcode from `postcodes`
WHERE postcode NOT REGEXP '^w(c|$)'

The piece of code above is about a single character as asked in the question.上面的一段代码是关于问题中询问的单个字符 For people who end up here in this thread and look for a negative lookahead with a full word it is also possible in contrast with the other answer from @Wiktor Stribiżew对于在此线程中结束并寻找带有完整单词的否定前瞻的人来说,这与@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|$)'

OR you can go for a subquery with NOT IN或者您可以使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM