Home > front end >  Vb.net regex don't match if string starts with a P and contains an underscore
Vb.net regex don't match if string starts with a P and contains an underscore

Time:08-06

My regex is \[([^P]*[^_])]. I would like to match [ABCD] or [ABCD_D] for example, but I don't want to match if the first character in brackets starts with a P and contains an underscore. So if I came across [PABCD_23] or [Pblah_blah] regex would not match. Right now, the regex I have won't match if string contains P anywhere in the string, I think the underscore part is working.

CodePudding user response:

You might use:

\[(?!P[^][_]*_)[^][]*]

Explanation

  • \[ Match [
  • (?! Negative lookahead, assert what is to the right is not
    • P[^][_]*_ Match a P, optionally any char except [ ] _ and then match _
  • ) Close the lookahead
  • [^][]* Optionally match any char except [ and ]
  • ] Match ]

See a regex demo.

CodePudding user response:

Maybe it can be done like this?

\[([^P_]).*]
  • Related