Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple Regex question / multiple matches

Tags:

c#

regex

Newbie Regex question / C#:

Consider (.*)=(.*) and how it would match "A = B = C"

I exepected to get two match objects back since there are two ways to group and match:

(A = B) = (C)   

     or 

(A) = (B = C)

However I get back only one match object (the first case). So I guess I don't understand why the match collection is a collection - since I can't seem to get more than one item into it. Can someone explain ?


fyi - for the above test I just used the immed window:

?Regex.Matches("A = B = C", "(.*)=(.*)").Count
 1

?Regex.Matches("A = B = C", "(.*)=(.*)")[0].Groups[1].Captures[0]
 Value: "A = B"

?Regex.Matches("A = B = C", "(.*)=(.*)")[0].Groups[1].Captures[1]
 Value: "C"
like image 671
tpascale Avatar asked Apr 08 '26 19:04

tpascale


1 Answers

The collection returned by Matches contains consecutive matches, not alternative matches for the same section of the string. So if you pass in a string like "A = B\nC = D", you'll get back two matches: one for "A = B" and one for "C = D" (as . does not match line breaks).

like image 121
sepp2k Avatar answered Apr 10 '26 11:04

sepp2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!