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);
}
}
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With