Ms. Corlib
Ms. Corlib

Reputation: 5213

Why isn't this getting the stuff between brackets?

I'm looking at

var r = new Regex(@"\{(.*?)\}");
var m = r.Match("{abc}");
Console.WriteLine(m.Groups[0].Value);

and it's getting me "{abc}" whereas I expected it to get the stuff in between brackets, "abc". Isn't that the Value?

Also, I don't know if this is possible, but I want to get the outermost paranthesis in the case that they are nested, e.g.

"{{abc}" --> "{abc"

Upvotes: 1

Views: 52

Answers (1)

ΩmegaMan
ΩmegaMan

Reputation: 31686

it's getting me "{abc}" whereas I expected it to get the stuff in between brackets, "abc". Isn't that the Value?

No, look at Groups[1] which is the first match capture instead, while Groups[0] is the whole match.

The match capture is what is between the (...) in a regex match and those are numbered in successive order from 1 to n. While the other items are matched but not captured and found in the whole match at index 0.


"{{abc}" --> "{abc"

Try {+([^}]+)} as a pattern for the + next to the { tells the regex parser to find 1 or more of {.


Note sometimes one doesn't want to deal with match captures indexes, then one can use named match captures such as this literal example:

{+(?<TextBetweenTheBrackets>[^}]+)}

and then extract the value between the brackets as

Groups["TextBetweenTheBrackets"].value

Upvotes: 3

Related Questions