Search Results for

    Show / Hide Table of Contents

    Regex Constraint

    RegexConstraint tests that a string matches a regular expression pattern.

    Usage

    Does.Match(string pattern)
    Does.Not.Match(string pattern)
    

    Modifiers

    .IgnoreCase
    

    Examples

    [Test]
    public void RegexConstraint_Examples()
    {
        string phrase = "Make your tests fail before passing!";
    
        Assert.That(phrase, Does.Match("Make.*tests.*pass"));
        Assert.That(phrase, Does.Match("make.*tests.*PASS").IgnoreCase);
        Assert.That(phrase, Does.Not.Match("your.*passing.*tests"));
    }
    

    Common Pattern Examples

    [Test]
    public void RegexConstraint_Pattern_Examples()
    {
        // Email validation (simplified)
        Assert.That("user@example.com", Does.Match(@"^[\w.-]+@[\w.-]+\.\w+$"));
    
        // Phone number format
        Assert.That("555-123-4567", Does.Match(@"^\d{3}-\d{3}-\d{4}$"));
    
        // Starts with digit
        Assert.That("42 is the answer", Does.Match(@"^\d"));
    
        // Contains only letters and spaces
        Assert.That("Hello World", Does.Match(@"^[a-zA-Z\s]+$"));
    
        // ISO date format
        Assert.That("2024-01-15", Does.Match(@"^\d{4}-\d{2}-\d{2}$"));
    }
    

    Notes

    1. The pattern uses .NET regular expression syntax.
    2. The entire string does not need to match - use ^ and $ anchors if you need a full match.
    3. For simple substring matching, consider using SubstringConstraint instead.

    See Also

    • Substring Constraint
    • StartsWith Constraint
    • EndsWith Constraint
    • Edit this page
    In this article
    Back to top Generated by DocFX | Copyright (c) 2018- The NUnit Project - Licensed under CC BY-NC-SA 4.0