All rules
CA1875Performance Enabled by default: As suggestion

Use Regex.Count

Use Regex.Count

Microsoft docs

Description

System.Text.RegularExpressions.Regex.Count is simpler and faster than Regex.Matches(...).Count. The Count() method is optimized for counting matches without materializing the full System.Text.RegularExpressions.MatchCollection. Calling Matches() and then accessing .Count does unnecessary work that can impact performance.

Cause

The System.Text.RegularExpressions.MatchCollection.Count property of the MatchCollection from System.Text.RegularExpressions.Regex.Matches is used to get the count of matches.

How to fix violations

Replace calls to Regex.Matches(...).Count with Regex.Count(...).

A *code fix* that automatically performs this transformation is available.

Example

using System.Text.RegularExpressions;

class Example
{
    public int CountWords(string text)
    {
        // Violation
        return Regex.Matches(text, @"\b\w+\b").Count;
    }
}

using System.Text.RegularExpressions;

class Example
{
    public int CountWords(string text)
    {
        // Fixed
        return Regex.Count(text, @"\b\w+\b");
    }
}

When to suppress

It's safe to suppress a warning from this rule if performance isn't a concern or if you're targeting a version of .NET that doesn't include Regex.Count (prior to .NET 7).

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0