Edit

Share via


CA1874: Use 'Regex.IsMatch'

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

Cause

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

Rule description

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 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:

using System.Text.RegularExpressions;

class Example
{
    public bool IsValidEmail(string email)
    {
        // Violation
        return Regex.Match(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$").Success;
    }
}
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:

using System.Text.RegularExpressions;

class Example
{
    public bool IsValidEmail(string email)
    {
        // Fixed
        return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
    }
}
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.

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

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

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

See also