Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to not include something in regex capture group

Tags:

c#

regex

Given:

var input = "test <123>";

Regex.Matches(input, "<.*?>");

Result:

<123>

Gives me the result I want but includes the angle brackets. Which is ok because I can easily do a search and replace. I was just wondering if there was a way to include that in the expression?

like image 927
Rod Avatar asked Aug 15 '17 18:08

Rod


1 Answers

You need to use a capturing group:

var input = "test <123>";
var results = Regex.Matches(input, "<(.*?)>")
    .Cast<Match>()
    .Select(m => m.Groups[1].Value)
    .ToList();

The m.Groups[1].Value lets you get the capturing group #1 value.

And a better, more efficient regex can be <([^>]*)> (it matches <, then matches and captures into Group 1 any zero or more chars other than > and then just matches >). See the regex demo:

enter image description here

like image 87
Wiktor Stribiżew Avatar answered Sep 29 '22 08:09

Wiktor Stribiżew