Kevin
Kevin

Reputation: 1

Regex - match all strings with specific exceptions

I have a lot of strings which have similar values. I need to write a regex that will keep all values except those that start with a specific substring, anyone know how I can do this.

For example, assume my string values are :

foo_bar
foo_baz
foo_bar_baz
foo_baz_bar
bar_baz
bar_foo

I can write a regex that will capture all of the above strings easily :

(foo_.*|bar_.*)

But supposing I have reasons for dropping anything that contains "foo_baz" and keep all the others. i.e. my results would be :

foo_bar
foo_bar_baz
bar_baz
bar_foo

Is there any easy way to achieve this without explicitly listing each of the strings I want to keep?

Thanks.

Upvotes: 0

Views: 44

Answers (1)

Bastien Jansen
Bastien Jansen

Reputation: 8846

You can use a negative lookahead:

^(?!foo_baz).*$

See https://regex101.com/r/jBCSjR/1

Or, depending on your programming language, it could be easier to filter out values using startsWith() or any equivalent.

Upvotes: 1

Related Questions