using-generated-regex
/using-generated-regex
Implements compile-time regex using GeneratedRegexAttribute Source Generator. Use when working with Regex patterns for better performance and AOT compatibility.
- Author
- christian289 ↗
- Repository
- dotnet-with-claudecode ↗
- Licence
- MIT
- Last repository change
- 21.07.2026
Assessment and security
- Files in this package
- 1
- Scripts
- 0
- HTML comments
- 0
- URLs in SKILL.md
- 0
No signals detected. Repository changed on 21.07.2026, without references to retired models or APIs.
MIT, open: use and modify while retaining author attribution.
What it does and when to use it
Implements compile-time regex using GeneratedRegexAttribute Source Generator. Use when working with Regex patterns for better performance and AOT compatibility.
Original author description
Implements compile-time regex using GeneratedRegexAttribute Source Generator. Use when working with Regex patterns for better performance and AOT compatibility.
How it works
- Why GeneratedRegex?
- Basic Pattern
- Common Patterns
- Migration from Runtime Regex
- RegexOptions
- WPF Validation Example
- GlobalUsings.cs
- Checklist
SKILL.md preview
---
description: Implements compile-time regex using GeneratedRegexAttribute Source Generator. Use when working with Regex patterns for better performance and AOT compatibility.
user-invocable: false
model: haiku
---
# Using GeneratedRegex (Source Generator)
Use `GeneratedRegexAttribute` for compile-time regex generation instead of runtime `new Regex()`.
## Why GeneratedRegex?
| Aspect | Runtime Regex | GeneratedRegex |
|--------|--------------|----------------|
| Compilation | Runtime | Compile-time |
| Performance | Slower first match | Pre-compiled, faster |
| AOT Support | Limited | Full support |
| Memory | Allocates at runtime | No runtime allocation |
| .NET Version | All | .NET 7+ |
---
## Basic Pattern
```csharp
public partial class EmailValidator
{
[GeneratedRegex(@"^[\w\.-]+@[\w\.-]+\.\w+$", RegexOptions.IgnoreCase)]
private static partial Regex EmailPattern();
public bool IsValidEmail(string email)
{
return EmailPattern().IsMatch(email);
}
}
```
**Requirements:**
- Class must be `partial`
- Method must be `static partial` returning `Regex`
- .NET 7 or later
---
## Common Patterns
### Email Validation
```csharp
public partial class ValidationPatterns
{
[GeneratedRegex(@"^[\w\.-]+@[\w\.-]+\.\w+$", RegexOptions.IgnoreCase)]
public static partial Regex Email();
}
```
### Phone Number
```csharp
[GeneratedRegex(@"^\d{3}-\d{3,4}-\d{4}$")]
public static partial Regex PhoneNumber();
```
### URL Pattern
```csharp
[GeneratedRegex(@"^https?://[\w\.-]+(?:/[\w\.-]*)*$", RegexOptions.IgnoreCase)]
public static partial Regex Url();
```
### Whitespace Normalization
```csharp
[GeneratedRegex(@"\s+")]
private static partial Regex WhitespacePattern();
public string NormalizeWhitespace(string input)
{
return WhitespacePattern().Replace(input, " ");
}
```
---
## Migration from Runtime Regex
### Before (Runtime)
```csharp
// Anti-pattern: Runtime compilation
public class Validator
{
private static readonly Regex _emailRegex =
new(@"^[\w\.-]+@[\w\.-]+\.\w+$", RegexOptions.Compiled);
public bool IsValid(string email)
{
return _emailRegex.IsMatch(email);
}
}
```
### After (Source Generator)
```csharp
// Best practice: Compile-time generation
public partial class Validator
{
[GeneratedRegex(@"^[\w\.-]+@[\w\.-]+\.\w+$")]
private static partial Regex EmailPattern();
public bool IsValid(string email)
{
return EmailPattern().IsMatch(email);
}
}
```
---
## RegexOptions
```csharp
// Multiple options
[GeneratedRegex(@"pattern", RegexOptions.IgnoreCase | RegexOptions.Multiline)]
private static partial Regex MultiOptionPattern();
// With timeout (for untrusted input)
[GeneratedRegex(@"complex.*pattern", RegexOptions.None, matchTimeoutMilliseconds: 1000)]
private static partial Regex SafePattern();
```
---
## WPF Validation Example
```csharp
public partial class FormViewModel : ObservableValidator
{
[GeneratedRegex(@"^[\w\.-]+@[\w\.-]+\.\w+$", RegexOptions.IgnoreCase)]
private static partial Regex EmailPattern();
[GeneratedRegex(@"^\d{3}-\d{3,4}-\d{4}$")]
private static partial Regex PhonePattern();
[CustomValidation(typeof(FormViewModel), nameof(ValidateEmail))]
[ObservableProperty] private string _email = string.Empty;
[CustomValidation(typeof(FormViewModel), nameof(ValidatePhone))]
[ObservableProperty] private string _phone = string.Empty;
public static ValidationResult? ValidateEmail(string email, ValidationContext context)
{
if (string.IsNullOrEmpty(email))
return new ValidationResult("Email is required");
if (!EmailPattern().IsMatch(email))
return new ValidationResult("Invalid email format");
return ValidationResult.Success;
}
public static ValidationResult? ValidatePhone(string phone, ValidationContext context)
{
if (string.IsNullOrEmpty(phone))
return ValidationResult.Success; // Optional field
if (!PhonePattern().IsMatch(phone))
return new ValidationResult("Format: 000-0000-0000");
return ValidationResult.Success;
}
}
```
---
## GlobalUsings.cs
```csharp
global using System.Text.RegularExpressions;
```
---
## Checklist
- [ ] Class is marked as `partial`
- [ ] Method is `static partial` returning `Regex`
- [ ] Pattern string is valid regex
- [ ] Target framework is .NET 7+
- [ ] Consider `RegexOptions` for case sensitivity
- [ ] Add timeout for untrusted input patterns
Versions
The database has no other skills named using-generated-regex.
Database snapshot: 13.11.2026 · package version ae7e7e3fec78 (SHA-256 digest of the entire package)
Downloads in the last 30 days: 0 · ranking
Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.
Similar skills
- 100dotnet-aot-analysis
Analyzes and configures a .NET project or solution for Native AOT compatibility. Orchestrates source generator skills and applies AOT settings. Also use when the user mentions "AOT," "native AOT," "trimming," "publish AOT," "AOT compatibility," or "ahead-of-time compilation."… - 100regex-tester
Validate, test, and debug regular expressions by executing them against sample inputs. Use when asked to build, verify, or explain a regex pattern. - 100dotnet-source-gen-options-validation
Converts options validation to use the compile-time source generator for AOT-compatible, reflection-free validation. Also use when the user mentions "OptionsValidator," "options validation source gen," "AOT options validation," "compile-time validation," "ValidateDataAnnotations… - 100regex-master
Use this skill when building, explaining, or debugging regular expressions for pattern matching, validation, or text extraction. Trigger phrases: ''write a regex'', ''match this pattern'', ''validate this format'', ''extract from text''. Not for natural language parsing or full… - 100regex-construction-and-testing
Builds, explains, and tests regular expressions for a named engine (PCRE, Python re, JavaScript, Java, Go RE2, .NET, POSIX grep/sed), with a positive and negative test table, anchoring, and checks for catastrophic backtracking (ReDoS). Use when writing or debugging a regex,… - 100regex
Write, explain, test, and debug regular expressions, and build them iteratively against real sample input. Use when users want a regex/pattern to match or extract text, ask why a pattern isn't matching, need to validate emails/URLs/dates/phone numbers, or want to do…