Language
Edit

CA2028: Avoid redundant 'Regex.IsMatch' call before 'Regex.Match'

Property Value
Rule ID CA2028
Title Avoid redundant Regex.IsMatch call before Regex.Match
Category Reliability
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 10 No
Enabled by default in .NET 11 As suggestion
Applicable languages C# and Visual Basic

Cause

Code calls IsMatch and then calls Match with the same input and pattern.

Rule description

Regex.IsMatch and Regex.Match both evaluate the regular expression. Call Regex.Match once and check the returned Group.Success property to avoid the redundant evaluation.

How to fix violations

Replace the Regex.IsMatch call with one Regex.Match call. Use Match.Success to check whether the input matches the pattern.

Examples

The following code shows a violation of CA2028:

if (Regex.IsMatch(input, pattern))
    return Regex.Match(input, pattern).Value;
If Regex.IsMatch(input, pattern) Then
    Return Regex.Match(input, pattern).Value
End If

Call Regex.Match once:

var match = Regex.Match(input, pattern);
return match.Success ? match.Value : string.Empty;
Dim match = Regex.Match(input, pattern)
Return If(match.Success, match.Value, String.Empty)

When to suppress warnings

Suppress the warning only when you intentionally evaluate the same regular expression more than once.

Suppress a warning

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

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

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

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

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

See also