Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why check for Match.Success

Tags:

c#

regex

In a code sample I saw a foreach loop going over the matches of a regex. Inside the loop there was a check for match.Success. But wouldn't all these matches be a success? Otherwise they wouldn't be matches, would they?

Am I wrong to think that (in this situation) the check is redundant?

var regex = new Regex(pattern);
var matches = regex.Matches(input);
var list = new List<string>();
foreach (Match m in matches) {
    if (m.Success) {
        list.Add(m.Value);
    }
}
like image 881
fwend Avatar asked Jan 21 '18 09:01

fwend


2 Answers

The Regex.Match() method and related Match.NextMatch() method always returns a Match object instance. However, you can only determine if the regular expression matched the input text by checking the Match.Success property.

Gets a value indicating whether the match is successful.

However, as Marc pointed out it is also possible to use the Matches() method to get an entire collection of (only true) Match objects at once, in which case checking the property would be redundant.

So, yes in the code snippet you (finally) provided the Success check is unnecessary.

like image 82
NightOwl888 Avatar answered Sep 18 '22 17:09

NightOwl888


If they are looping on the return value from Regex.Matches, then yes: the check is redundant. Matches() uses the same object that Match() uses, and with Match() it isn't known whether you have a match or not - hence the .Success property to tets that. With Matches(), you only get successes, but: the object model is still the same.

You don't need to check .Success when using Matches()

like image 31
Marc Gravell Avatar answered Sep 18 '22 17:09

Marc Gravell