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
- The pattern uses .NET regular expression syntax.
- The entire string does not need to match - use
^and$anchors if you need a full match. - For simple substring matching, consider using SubstringConstraint instead.