Reputation: 11243
I need regular expression that matches a pattern or is empty.
Right now I have an expression...
"\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x"
... which matches US phone numbers. However, it is valid for the string I'm testing to be empty. If the string has any value in it at all, it must match the expression.
I have other patterns which match US postal codes, etc that need the same conditional.
What is the best way to achieve this in the same expression?
Clarification: I am using the RegexValidator in the Validation Application Block from Microsoft. An example of using this is as follows:
[StringLengthValidator(0, 100, MessageTemplate = "Email must be between {3} and {5}")]
[RegexValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", MessageTemplate = "Valid Email Required.")]
public string EmailAddress
{
get { return _EmailAddress; }
set { SetValue<string>(ref _EmailAddress, value); }
}
This is why I need the solution to be in one expression.
Upvotes: 13
Views: 21900
Reputation: 75222
Try this:
@"^(?:(\()?\d{3}(?(1)\)|[-\s.])\d{3}[-\s.]\d{4})?$"
The (?(1)\)|[-\s.])
part is a conditional construct. It says "If there was a '(' at the beginning (which we know because group #1 matched something), match a ')' here; otherwise match a hyphen, whitespace or dot." And wrapping the whole thing in (?:...)?
allows it to match an empty string, just as Kevin said; if that didn't work for you, you must have misplaced one of the parens (or maybe one of the backslashes).
I added the ^
and $
anchors for testing purposes; in a validator control they shouldn't be needed.
Upvotes: 1
Reputation: 10180
Wrap the entire regex in parens and place a ? at the end:
(\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x)?
Upvotes: 30