Regex to match exact number in string without lookahead or lookbehind

Let’s say I’m looking for a specific number in string with newlines: 1n2n4n5n7n8n9n12n13

Lookahead and lookbehind works perfectly with something like:

(?<![0-9])12(?![0-9])

See Regex 101 demo.

However, I need a workaround for the MySQL REGEXP, as it does not support patterns with lookarounds.

Answer

If (?<![0-9])12(?![0-9]) works for you in an online regex engine, the following regex must work for you in REGEXP pattern that is POSIX based:

(^|[^0-9])12($|[^0-9])

Or, you may use word boundaries:

[[:<:]]12[[:>:]]

See the regex demo.

Details:

  • (^|[^0-9]) – start of string or a non-digit char
  • [[:<:]] – leading word boundary
  • 12 – a specific numeric value, 12 here
  • [[:>:]] – trailing word boundary
  • ($|[^0-9]) – end of string or a non-digit.

Leave a Reply

Your email address will not be published. Required fields are marked *