brane
brane

Reputation: 675

Regex Match string prefix, but not multiple strings containing this prefix

I need a regex which matches

any_

But which does not match any of the strings below

any_group1
any_group2

I tried

(?=.*any_.*)^((?!any_group1).)*$^((?!any_group1).)*$

Upvotes: 1

Views: 151

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

You might also use a negative lookahead (?! to assert what is on the right is not group1 or group2:

\bany_(?!group[12]\b)

Regex demo

That will match:

  • \b Word boundary
  • any_ Match literally
  • (?!group[12]\b) Negative lookahead to assert what is on the right is not group1 or group 2 followed by a word boundary

Upvotes: 1

zipa
zipa

Reputation: 27869

Well this should do it, using Negative Lookbehind:

\bany_.*(?<!group[1-2])\b$

Regex 101.

Upvotes: 2

Related Questions