一个正则表达式匹配不以...开头的字符串,并且不以

时间:2016-07-05 10:56:27

标签: php mysql regex

我正在尝试找到与单词匹配但不以特定字符开头/结尾的正则表达式。

实施例: 搜索字是迷你

它应匹配:

mini
mini abc
mini-abc (- could be anything else but not [a-zA-Z0-9])
abc mini
abc-mini (- could be anything else but [a-zA-Z0-9])
abc mini abc
abcminiabc-mini (- could be anything else but not [a-zA-Z0-9])
mini-abcminiabc (- could be anything else but not [a-zA-Z0-9])
miniabc-mini (- could be anything else but not [a-zA-Z0-9])
mini-miniabc (- could be anything else but not [a-zA-Z0-9])
abcmin-mini (- could be anything else but not [a-zA-Z0-9])
mini-abcmini (- could be anything else but not [a-zA-Z0-9])

但不是:

miniabc
abcmini
abcminiabc
miniabc abc
abc abcmini
abcminiabc abc
abc abcminiabc

我尝试过这样的事情:

^(.*)([^a-zA-Z0-9]{0,1})MINI([^a-zA-Z0-9]{0,1})(.*)$

但这似乎不起作用,因为这也符合'miniabc','abcmini','abcminiabc',这不是我想要的。

(语言是PHP,以防在MySQL中无法使用。)

1 个答案:

答案 0 :(得分:6)

您可以在PHP(PCRE)中使用基于外观的正则表达式:

(?<![a-zA-Z0-9])mini(?![a-zA-Z0-9])
  • (?![a-zA-Z0-9]) 否定前瞻断言下一个位置没有[a-zA-Z0-9]个字符
  • (?<![a-zA-Z0-9]) 负面后卫断言前一个位置没有[a-zA-Z0-9]个字符

More on lookarounds regular expressions

RegEx Demo