A 5-digit zip codeAs a basic example let's build a 5 digit zip code regular expression that matches an entire string for one 5-digit U.S. zip code.
// Default constructor, there are no overloads
RegexBuilder builder = new RegexBuilder();
// Methods are chaining, so we put each declaration on its own line for clarity
builder
.StartOfAString()
.AnyDecimalDigit().Quantifier(5) // five required digits
.EndOfAString();
string text = builder.ToString();
Regex regex = builder.CreateRegex();
The value of
text is the actual expression text, which in this case is "^\d{5}$". Calling
CreateRegex on the instance of
builder creates a consumable
Regex object (this method also has an overload where you can supply
RegexOptions flags).
A 9-digit zip codeSimilar to our last example but with an added twist of a separator and an additional 4 digits.
// Default constructor, there are no overloads
RegexBuilder builder = new RegexBuilder();
// Methods are chaining, so we put each declaration on its own line for clarity
builder
.StartOfAString()
.AnyDecimalDigit().Quantifier(5) // five required digits
.MatchCharacterSet(' ', '-') // the 5 and 4 digit groups must be separated by a space or a comma
.AnyDecimalDigit().Quantifier(4) // four required digits
.EndOfAString();
This should generate the regex: "^\d{5}[ -]\d{4}$"
A 5-digit zip code with an optional 4-digit extensionFinally, let's make use of a logical group (capture group) and make the last 4 digits and it's separator optional.
// Default constructor, there are no overloads
RegexBuilder builder = new RegexBuilder();
// Methods are chaining, so we put each declaration on its own line for clarity
builder
.StartOfAString()
.AnyDecimalDigit().Quantifier(5) // five required digits
.LogicalGrouping(optionalExtension => optionalExtension // the optional 4 digits and separator
.MatchCharacterSet(' ', '-').Optional() // separator is optional, but must be a space or comma if it exists
.AnyDecimalDigit().Quantifier(4) // the last 4 digits
).Optional() // close the grouping and make it optional
.EndOfAString();
This should generate the regex: "^\d{5}([ -]?\d{4})?$"