Flash Flash - 5 months ago 19
MySQL Question

A regex to match string that doesnt start with ... and doesnt end with

I'm trying to find a Regex that matches a word but doesn't start/end with a specific character.

Example:
The Search word is mini

it should match:

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])


but not:

miniabc
abcmini
abcminiabc
miniabc abc
abc abcmini
abcminiabc abc
abc abcminiabc


I've tried something like this:

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


But that doesn't seems to work since this also matches 'miniabc', 'abcmini', 'abcminiabc', which isn't what i wanted.

(Language is PHP in case it isn't possible in MySQL.)

Answer

You can use lookaround based regex in PHP (PCRE):

(?<![a-zA-Z0-9])mini(?![a-zA-Z0-9])
  • (?![a-zA-Z0-9]) is negative lookahead that asserts that next position doesn't have [a-zA-Z0-9] characters
  • (?<![a-zA-Z0-9]) is negative lookbehind that asserts that previous position doesn't have [a-zA-Z0-9] characters

More on lookarounds regular expressions

RegEx Demo