Home > Mobile >  reverse lookup inverted regex
reverse lookup inverted regex

Time:12-25

I am dealing with a string similar to this:

ABCD_EFGHI-78-32#1-R77.2_301009_1_AB3_CD

delimiter is: _

I need a regex that wont match if second portion [EFGHI-98-32#1-R77.2] contains case insensitive "TesT" anywhere within that block, but that would match for any other case.

So I started like this:

^[A-Z]{4,5}_(?i)(?<=_)(.*)(?=TEST)(?-i). ?(?=_)_\d{6}_\d_.{2}\d_.{2}

but I don't know how to invert ?=TEST to ?!=TEST and I noted that there are Group and Match differences too.

I would appreciate some assistance with formulation of regex so that the whole string is match except if second block contains any variation of word test between delimiters.

for ex. this one works but only if second block starts with word test:

^[A-Z]{4,5}_((?i)(?!test)(?-i). ?(?=_))_\d{6}_\d_.{2}\d_.{2}$

Thanks!

CodePudding user response:

You have to test at every character that test does not appear there. So your second group should basically be

(?:(?!test)[^_]) 

Incorporating it into your regexp, and adding the case insensitivity flag,

^[A-Z]{4,5}_(?:(?!(?i)test)[^_]) _\d{6}_\d_[^_]{2}\d_[^_]{2}

(you probably don't want .{2}, because it would accept __, for example — so explicitly restricting the character set makes sense)

CodePudding user response:

Here is a quick fix for your pattern:

^[A-Z]{4,5}_((?![^_]*(?i:test))[^_]*)_\d{6}_\d_.{2}\d_.{2}$

See the regex demo. I only replaced the Group 2 pattern:

  • (?![^_]*(?i:test)) - a negative lookahead that fails the match if there are zero or more chars other than _ followed with a case insensitive test string (note the inline modifier group is used to make that pattern a bit shorter, and it is also more portable)
  • [^_]* - any zero or more chars other than underscores.
  • Related