Simple Regex Question / Multiple Matches

New Regex / C # question:

Consider (. *) = (. *) And how it will correspond to "A = B = C"

I am exepected to get two matching objects back, as there are two ways to group and match:

(A = B) = (C)   

     or 

(A) = (B = C)

However, I return only one matching object (the first case). Therefore, I think I don’t understand why the collection of matches is a collection, since I cannot get more than one item. Can someone explain?


fyi - for the above test, I just used the "immediate" 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"
+3
source share
5 answers

, Matches, , . , "A = B\nC = D", : "A = B" "C = D" ( . ).

+3

.* . , , . .* "A = B", "C" .*

, ? . .*? , .

+2

, , , , . , A = B , .

+2
source

This does not work.

If your input text is:

"A = B = C\r\nW = X = Z"

and your expression was

"([^=]?) = ([^=]?) = ([^=]?)"

then you will get some results. Please read the documentation!: - D

0
source

The quantifier * is greedy. This makes the first expression .*match many characters, so the expression will always match(A = B) = (C).

Using a non-greedy quantifier *?will match (A) = (B = C).

Try to use it!

0
source

All Articles