user3138879
user3138879

Reputation: 183

How to find a string which doesnot contain a specific using regular expression in c# .net

I have a long string.

Example
This is a dog.
This is a cat.
A cat and a cat is a pet animal.
A tiger is a wild animal.

Now I want the string which does not contain 'cat' but contain a animal. How can I do this using regex. I know that I have to use(?!) but how that i dont know. So the output would be

A tiger is a wild animal.

Upvotes: 3

Views: 65

Answers (2)

vks
vks

Reputation: 67968

^(?!.*\bThis\b).*$

Try this.See demo.

https://regex101.com/r/tJ2mW5/16

For you edited question use

^(?=.*\banimal\b)(?!.*\bcat\b).*$

See demo.

https://regex101.com/r/tJ2mW5/18

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626929

Here is an example using a negative look-behind:

var s1 = "This is a dog.\nThis is a cat.\nA cat and a cat is a pet animal.\nA tiger is a wild animal.";
 var rx = new Regex(@"^.*(?<!\bcat\b.*)$", RegexOptions.Multiline);
 var c = rx.Matches(s1).Cast<Match>().Select(d => d.Value.Trim()).ToList();

Output:

enter image description here

Upvotes: 0

Related Questions