使用regex [duplicate]在字符串中查找所有匹配

时间:2022-03-19 04:53:42

This question already has an answer here:

这个问题已经有了答案:

My input is

我的输入

This is <a> <test> mat<ch>.

Output should be

输出应该

1. <a>
2. <test>
3. <ch>

I have tried this

我试了

string input1 = "This is <a> <test> mat<ch>.";
var m1 = Regex.Matches(input1, @"<(.*)>");
var list = new List<string>();
foreach (Match match in m1)
{
    list.Add(match.Value);
}

This returns <a> <test> mat<ch> as single element in list.

这将返回 mat 为列表中的单个元素。

2 个解决方案

#1


10  

Make your regex non greedy

让你的正则表达式不贪婪

var m1 = Regex.Matches(input1, @"<(.*?)>");

Or use negation based regex

或者使用基于拒绝的regex

var m1 = Regex.Matches(input1, @"<([^>]*)>");

#2


3  

You can simply use the following regex

您可以使用以下regex

(<.*?>)
  //^^ Using Non greedy 

If there's any case like of <test<a<b>>>

如果有 >>的情况

then you can simply use

然后你可以简单地使用

(<[^>]>)

Output:

输出:

<b>

#1


10  

Make your regex non greedy

让你的正则表达式不贪婪

var m1 = Regex.Matches(input1, @"<(.*?)>");

Or use negation based regex

或者使用基于拒绝的regex

var m1 = Regex.Matches(input1, @"<([^>]*)>");

#2


3  

You can simply use the following regex

您可以使用以下regex

(<.*?>)
  //^^ Using Non greedy 

If there's any case like of <test<a<b>>>

如果有 >>的情况

then you can simply use

然后你可以简单地使用

(<[^>]>)

Output:

输出:

<b>