为何需检查Match.Success?遍历Regex匹配时该检查是否冗余?
Is checking
Match.Success redundant when iterating over Regex.Matches() results? Great question! Let's break this down clearly:
Yes, that if (m.Success) check is completely redundant in your code. Here's why:
- The
Regex.Matches()method returns aMatchCollectionthat only contains successfully matchedMatchobjects. By design, every entry in this collection is guaranteed to haveSuccess == true—failed matches are never added to the collection at all. - The collection is built specifically to surface only the results where the regex found a valid match against your input string. There's no scenario where a
Matchfrom this collection would have aSuccessvalue offalse.
Looking at your original code snippet:
var regex = new Regex(pattern); var matches = regex.Matches(input); var list = new List<string>(); foreach (Match m in matches) { if (m.Success) { // This check is unnecessary list.Add(m.Value); } }
You can safely simplify it to remove the redundant check:
var regex = new Regex(pattern); var matches = regex.Matches(input); var list = new List<string>(); foreach (Match m in matches) { list.Add(m.Value); }
Or even use LINQ for a more concise version (available in .NET 3.5 and later):
var list = new Regex(pattern).Matches(input) .Cast<Match>() .Select(m => m.Value) .ToList();
Just to clarify when you would need to check Match.Success: This only becomes necessary if you're manually iterating using Match.NextMatch(), like this:
var match = regex.Match(input); while (match.Success) { list.Add(match.Value); match = match.NextMatch(); }
Here, NextMatch() can return a failed match once there are no more results to find, so the check is required to terminate the loop properly.
内容的提问来源于stack exchange,提问作者fwend
相关产品推荐
相关产品推荐

