Why check Match.Success

In the sample code, I saw a loop foreachgoing through a matches regex. Inside the loop there was a check for match.Success. But will not all of these matches be successful? Otherwise, they do not match, right?

Am I mistaken in thinking that (in this situation) verification 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);
    }
}
+4
source share
2 answers

If they fixate on the return value from Regex.Matches, then yes: the check is redundant. Matches()uses the same object that it uses Match(), but with Match()it is not known whether you have a match or not - therefore, a property .Successfor this. With Matches()you get only success, but: the object model remains the same.

.Success Matches()

+1

Regex.Match() Match. NextMatch() Match. , , Match.Success.

, , .

, , Matches(), ( true) , .

, (), Success .

+2

Source: https://habr.com/ru/post/1692482/


All Articles