Skip to content

[Analyzer]: Regex.IsMatch guarding Regex.Match #111239

@stephentoub

Description

@stephentoub

In looking through various code bases, I've seen the following pattern repeatedly:

if (Regex.IsMatch(pattern))
{
    Match m = Regex.Match(pattern);
    ...
}

That just doubles the work involved when there is a match. It should instead be:

if (Regex.Match(pattern) is { Success: true } m)
{
    ...
}

or something similar. We should have an analyzer that flags these duplicative guards and a fixer that transforms into something like the latter.

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Text.RegularExpressionscode-analyzerMarks an issue that suggests a Roslyn analyzercode-fixerMarks an issue that suggests a Roslyn code fixerhelp wanted[up-for-grabs] Good issue for external contributorsin-prThere is an active PR which will close this issue when it is merged

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions