14

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Manjay_TBAG
  • 2,176
  • 3
  • 23
  • 43

2 Answers2

20

Make your regex non greedy

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

Or use negation based regex

var m1 = Regex.Matches(input1, @"<([^>]*)>");
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
vks
  • 67,027
  • 10
  • 91
  • 124
  • 1
    @vks This solution worked. Can you please tell what is the significance of ? in this regex? – Manjay_TBAG Oct 27 '15 at 11:32
  • @TBAG when you use `?` it will stop at the first instance of `>` .If you dont it will be greedy and will go upto last instance of `>` – vks Oct 27 '15 at 11:35
  • in your regex `<(.*)>` the part `.*` will try to match as long as possible. since `.` is any character including `>` then it will go until last `>` character thus will give you all matches at once. when you use `.*?` is will match as least as possible so when you reach first `>` thats the part of the pattern so it will stop there and first match becomes `` forexample @TBAG – M.kazem Akhgary Oct 27 '15 at 11:35
  • Note that this regex will not match balanced angle brackets. Can you have any? – Wiktor Stribiżew Oct 27 '15 at 11:39
  • @stribizhev did explain in comments..waiting for OP if he needs more – vks Oct 27 '15 at 11:41
  • @M.kazemAkhgary what does `Don't be so green eyed` mean? – Michael McGriff Oct 27 '15 at 13:37
  • @M.kazemAkhgary no worries, I figured it was something along those lines due to the color, just curious. – Michael McGriff Oct 27 '15 at 13:43
4

You can simply use the following regex

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

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

then you can simply use

(<[^>]>)

Output:

<b>
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54