Find all matches in a string using regex

My input

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

The exit should be

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

I 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 a separate item in the list.

+6
source share
2 answers

Make your regex not greedy

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

Or use negation-based regular expression

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

You can simply use the following regex

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

If there is such a case as <test<a<b>>>

then you can just use

 (<[^>]>) 

Output:

 <b> 
+3
source

All Articles