Add CA2028: Avoid redundant Regex.IsMatch before Regex.Match#54074
Closed
Add CA2028: Avoid redundant Regex.IsMatch before Regex.Match#54074
Conversation
Agent-Logs-Url: https://github.com/dotnet/sdk/sessions/f2805c05-ed61-44c4-b860-32962a4ce0fe Co-authored-by: danmoseley <6385855+danmoseley@users.noreply.github.com>
Copilot
AI
changed the title
[WIP] Address remaining feedback on PR #54071
Add CA2028: Avoid redundant Regex.IsMatch before Regex.Match
Apr 26, 2026
Member
|
No I didn't want a new PR. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Implements CA2028, a new Roslyn analyzer + C# code fixer that detects and eliminates redundant
Regex.IsMatchguards that are immediately followed byRegex.Matchwith equivalent operands — causing the regex engine to run twice unnecessarily.Before / After:
Analyzer (
AvoidRedundantRegexIsMatchBeforeMatch.cs)??=, ref/out mutations, and tuple deconstructionifbodies also checked for writes (not just block bodies)SymbolEqualityComparerrather than redundantGetMemberssymbol setsC# Fixer (
CSharpAvoidRedundantRegexIsMatchBeforeMatch.Fixer.cs)Two fix paths:
Match m = Regex.Match(...)inside the if body → replaced withis { Success: true } mpatternifcondition withispattern; includes safety check that the variable is not referenced after theifName-conflict detection covers locals, foreach variables, catch clauses, pattern designations, and lambda/local-function parameters.
Tests
83 tests covering: all static/instance/timeout overloads, both fix paths, no-diagnostic cases, VB smoke tests, named arguments, intervening writes, mutable receivers, ref/out mutations, readonly-field receiver reassignment, name-collision edge cases, and real-world patterns (else-if chains, foreach loops, const fields).
Original prompt
This pull request was created from Copilot chat.