Reputation: 23861
I have the following string:
Message 1 [V.Variable1] Message 2 [F.Field1] Message 3
Why does it work well in ex1 and doesn't in ex2?
var ex1 = Regex.Matches(message, @"\[F\.(?<name>.+)\]");
// the result `{[F.Field1]}` .. as expected
var ex2 = Regex.Matches(message, @"\[V\.(?<name>.+)\]");
// the result `{[V.Variable1] Message 2 [F.Field1]}` .. not as expected
When I'm trying to get the value of the group name
, it gives the expected result in ex1 which is Field1
but it returns nothing in ex2
Any idea?
Upvotes: 0
Views: 82
Reputation: 31524
You have to make the .+
lazy: \[V\.(?<name>.+?)\]"
(note the question mark). The second case doesn't work because the +
sign is greedy by default, and it will match as much as it can, in your case to the second closing square bracket from the second group.
Upvotes: 3