正则表达式可以匹配除特定给定字符串之外的所有内容(包括空字符串) [英] Regex to match anything (including the empty string) except a specific given string

查看:988
本文介绍了正则表达式可以匹配除特定给定字符串之外的所有内容(包括空字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个字符串是否包含"Kansas",后跟除" State"之外的其他任何内容.

I'd like to test whether a string contains "Kansas" followed by anything other than " 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 ,我相信答案是这样的:

For PCRE, I believe the answer is this:

'Kansas(?! State)'

但是Mysql的REGEXP似乎不喜欢这样.

But Mysql's REGEXP doesn't seem to like that.

附录:感谢 David M 概括了这个问题: 如何将PCRE转换为POSIX RE?

ADDENDUM: Thanks to David M for generalizing this question: How to convert a PCRE to a POSIX RE?

推荐答案

比大型正则表达式更有效(当然,这取决于您的数据和引擎的质量)

More efficient than that large regex (depending, of course, on your data and the quality of the engine) is

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

但是,如果堪萨斯州通常以堪萨斯州"的形式出现,您可能会发现更好的选择:

If Kansas usually appears in the form 'Kansas State', though, you may find this better:

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

这具有易于维护的附加优势.如果堪萨斯州很常见且文本字段很大,则效果会较差.当然,您可以根据自己的数据对它们进行测试,并告诉我们它们的比较方式.

This has the added advantage of being easier to maintain. It works less well if Kansas is common and text fields are large. Of course you can test these on your own data and tell us how they compare.

这篇关于正则表达式可以匹配除特定给定字符串之外的所有内容(包括空字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆