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

A way to not include something in a regex capture group

Given:

var input = "test <123>";

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

Result:

<123>

Gives me the result that I want, but includes angle brackets. This is normal because I can easily search and replace. I'm just wondering if there is a way to include this expression in the expression?

+6
source share
1 answer

You need to use a capture group:

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

m.Groups[1].Value allows you to get the value of capture group # 1.

And the best, more effective regular expression can be <([^>]*)>(it matches <, then matches and fixes in Group 1 any zero or more characters other than >, and then just matches >). See regex demo :

enter image description here

+4

All Articles