Home > Enterprise >  Regex - match number within a text that does not start with a certain string
Regex - match number within a text that does not start with a certain string

Time:07-07

I've searched through multiple answers on SO now, but most of them consider the beginning of the line as the whole string being looked upon, which doesn't serve my case, I think (at least all the answers I tried didn't work).

So, I want to match all codes within a text that are 7-digit long, start with 1 or 2, and are not prefixed by "TC-" and its lowercase variants.

Came up with the /(!?TC-){0}(1|2)\d{6}/g expression, but it doesn't work for not matching the codes that start with "TC-", and I don't know how can I prevent from selecting those. Is there a way to do that?

I've created an example pattern on Regexr: regexr.com/6p70c.

CodePudding user response:

You can assert not TC- to the left using negative lookbehind (?<! and omit the {0} quantifier as that makes it optional:

(?<!\bTC-)\b[12]\d{6}\b

Regex demo

  • Related