C#idiomatic C#
ca1874fundamentals/code-analysis/quality-rules

Code analysis

CA1874: Use 'Regex.IsMatch'

Learn about code analysis rule CA1874: Use 'Regex.IsMatch'

CA1874 Performance enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

The System.Text.RegularExpressions.Group.Success property of the result from System.Text.RegularExpressions.Regex.Match is used to check if a pattern matches.

Rule description

System.Text.RegularExpressions.Regex.IsMatch is simpler and faster than Regex.Match(...).Success. The IsMatch method is optimized for the case where you only need to know whether a match exists, rather than what the match is. Calling Match() and then checking System.Text.RegularExpressions.Group.Success does unnecessary work that can impact performance.

How to fix violations

Replace calls to Regex.Match(...).Success with Regex.IsMatch(...).

A code fix that automatically performs this transformation is available.

Example

The following code snippet shows a violation of CA1874:

csharp
using System.Text.RegularExpressions;

class Example
{
    public bool IsValidEmail(string email)
    {
        // Violation
        return Regex.Match(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$").Success;
    }
}
vb
Imports System.Text.RegularExpressions

Class Example
    Public Function IsValidEmail(email As String) As Boolean
        ' Violation
        Return Regex.Match(email, "^[^@\s]+@[^@\s]+\.[^@\s]+$").Success
    End Function
End Class

The following code snippet fixes the violation:

csharp
using System.Text.RegularExpressions;

class Example
{
    public bool IsValidEmail(string email)
    {
        // Fixed
        return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
    }
}
vb
Imports System.Text.RegularExpressions

Class Example
    Public Function IsValidEmail(email As String) As Boolean
        ' Fixed
        Return Regex.IsMatch(email, "^[^@\s]+@[^@\s]+\.[^@\s]+$")
    End Function
End Class

When to suppress warnings

It's safe to suppress a warning from this rule if performance isn't a concern.

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.

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

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

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

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

See also