Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What regular expression will match a pattern or be empty?

Tags:

regex

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.

like image 380
Sailing Judo Avatar asked Mar 24 '09 21:03

Sailing Judo


2 Answers

Try wrapping your regex with (?:<your_regex>)?.

like image 106
Andrew Hare Avatar answered Sep 23 '22 19:09

Andrew Hare


Wrap the entire regex in parens and place a ? at the end:

(\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x)?
like image 27
Kevin Crowell Avatar answered Sep 23 '22 19:09

Kevin Crowell