Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all matches in a string using regex [duplicate]

Tags:

c#

regex

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.

like image 606
Manjay_TBAG Avatar asked Oct 27 '15 11:10

Manjay_TBAG


1 Answers

Make your regex non greedy

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

Or use negation based regex

var m1 = Regex.Matches(input1, @"<([^>]*)>");
like image 59
vks Avatar answered Oct 10 '22 16:10

vks