Edit

Share via


CA1875: Use 'Regex.Count'

Property Value
Rule ID CA1875
Title Use Regex.Count
Category Performance
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 10 As suggestion

Cause

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

Rule description

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

How to fix violations

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

A code fix that automatically performs this transformation is available.

Example

The following code snippet shows a violation of CA1875:

using System.Text.RegularExpressions;

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

Class Example
    Public Function CountWords(text As String) As Integer
        ' Violation
        Return Regex.Matches(text, "\b\w+\b").Count
    End Function
End Class

The following code snippet fixes the violation:

using System.Text.RegularExpressions;

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

Class Example
    Public Function CountWords(text As String) As Integer
        ' Fixed
        Return Regex.Count(text, "\b\w+\b")
    End Function
End Class

When to suppress warnings

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).

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1875
// The code that's violating the rule is on this line.
#pragma warning restore CA1875

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1875.severity = none

For more information, see How to suppress code analysis warnings.

See also