Lord45
Lord45

Reputation: 77

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

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.

Upvotes: 0

Views: 79

Answers (2)

The fourth bird
The fourth bird

Reputation: 163362

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.

Upvotes: 1

Think2826
Think2826

Reputation: 211

Maybe it can be done like this?

\[([^P_]).*]

Upvotes: 0

Related Questions