You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何需检查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 a MatchCollection that only contains successfully matched Match objects. By design, every entry in this collection is guaranteed to have Success == 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 Match from this collection would have a Success value of false.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:35:22