Back to Skills

using-generated-regex

verified

Implements compile-time regex using GeneratedRegexAttribute Source Generator. Use when working with Regex patterns for better performance and AOT compatibility.

View on GitHub

Marketplace

dotnet-claude-plugins

christian289/dotnet-with-claudecode

Plugin

wpf-dev-pack

development

Repository

christian289/dotnet-with-claudecode
5stars

wpf-dev-pack/skills/using-generated-regex/SKILL.md

Last Verified

January 23, 2026

Install Skill

Select agents to install to:

Scope:
npx add-skill https://github.com/christian289/dotnet-with-claudecode/blob/main/wpf-dev-pack/skills/using-generated-regex/SKILL.md -a claude-code --skill using-generated-regex

Installation paths:

Claude
.claude/skills/using-generated-regex/
Powered by add-skill CLI

Instructions

# 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)

```cs

Validation Details

Front Matter
Required Fields
Valid Name Format
Valid Description
Has Sections
Allowed Tools
Instruction Length:
4013 chars