如何在c#.net中查找不包含特定使用正则表达式的字符串

时间:2015-03-24 10:21:33

标签: c# .net regex

我有一个很长的字符串。

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

现在我想要的字符串不包含' cat'但是含有一种动物。 我怎么能用正则表达式做到这一点。 我知道我必须使用(?!)但我不知道怎么做。 所以输出将是

A tiger is a wild animal.

2 个答案:

答案 0 :(得分:1)

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

试试这个。看看演示。

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

对于您编辑的问题使用

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

参见演示。

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

答案 1 :(得分:0)

以下是使用负面后卫的示例:

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();

输出:

enter image description here

相关问题