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.
Try wrapping your regex with (?:<your_regex>)?
.
Wrap the entire regex in parens and place a ? at the end:
(\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With