A Roslyn-based analyzer that validates string literal assignments against RegularExpression attribute constraints at compile time.
$ dotnet add package RegexStringLiterals.AnalyzerA Roslyn-based analyzer that validates string literal assignments against RegularExpression attribute constraints at compile time. This helps you catch configuration errors early�before runtime�improving code quality and reducing potential bugs.
The Regex String Literal Analyzer inspects code for properties, fields, or assignments annotated with the [RegularExpression(...)] attribute. It verifies that the string literal assigned matches the regular expression provided in the attribute. When a mismatch is found, the analyzer reports a diagnostic (warning by default, configurable via .editorconfig) so you can fix the issue immediately.
[RegularExpression] actually conform to the specified regex pattern.REGEX001) that indicates the expected pattern.Install the analyzer as a NuGet package so that it automatically runs during your build:
Using Package Manager Console:
Install-Package RegexStringLiterals.Analyzer
Using .NET CLI:
dotnet add package RegexStringLiterals.Analyzer
If you prefer to use a Visual Studio extension:
To use the analyzer in VS Code:
dotnet add package RegexStringLiterals.Analyzer
dotnet restore
Coming soon!
Once installed, the analyzer works automatically. For example, consider the following code snippet:
using System.ComponentModel.DataAnnotations;
public class TestClass {
[RegularExpression("red|green|blue")]
public string Color { get; set; } = "yellow"; // "yellow" does not match the pattern and will trigger a diagnostic.
}
Since "yellow" does not match the regex "red|green|blue", the analyzer will flag this assignment with a diagnostic message like:
REGEX001: Value 'yellow' does not match the pattern: red|green|blue.
If code fixes are available, you can trigger them via Visual Studio�s Quick Actions (usually by clicking the lightbulb icon).
The analyzer can flag invalid inputs for any regex strings but will only provide Qucik Action fixes for explicitly defined strings(such as the above example).
By default, the analyzer reports a warning when a mismatch is found. You can customize the severity (or even suppress the diagnostic) using an .editorconfig file in your project:
# Treat RegexStringLiteral diagnostics as errors
dotnet_diagnostic.REGEX001.severity = error
# Or to disable the analyzer:
dotnet_diagnostic.REGEX001.severity = none
Additionally, you may include other configuration settings as the project evolves.
Contributions are welcome! If you find a bug or have suggestions for improvements, please open an issue or submit a pull request on GitHub.
This project is licensed under the MIT License. Please see the LICENSE file for details.
See the CHANGELOG.md file for a detailed history of changes.