woods
woods

Reputation: 243

Check if the format of string matches desired format using Regex

I'm trying to write code that will take a given string and compare it to a certain format. This is what I'm using:

private static readonly Regex phoneNumber = new Regex(@"\d{3}-\d{3}-\d{4}");

public static bool VerifyPhoneNumber(string pNumber)
{
    return phoneNumber.IsMatch(pNumber);
}

The format is 000-000-0000, and it returns true when comparing it to 555-555-5555. I also have a MessageBox displaying pNumber and phoneNumber for comparison purpose. The Message Box displays: pNumber = 555-555-5555 and phoneNumber = \d{3}-\d{3}\d{4}

But that isn't the format I want. I want to use this format (000)000-0000. In order to use this format I changed phoneNumber to this:

private static readonly Regex phoneNumber = new Regex("(" + @"\d{3}" +  ")" + @"\d{3}-\d{4}");

But when I run this code and compare (555)555-5555 to it, it returns false. The MessageBox for this displays: pNumber = (555)555-5555 and phoneNumber = (\d{3})\d{3}-\d{4}

Now I don't know enough about Regex yet to fix this issue myself. Based on my research so far, the () are causing the issue. I believe its because () are used for regular expressions and dashes aren't. So, the dash doesn't mess anything up. My question is how can I change my code to fit my needs? How can I get the () in the code without issues?

Upvotes: 1

Views: 4770

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 385800

"(" is special to regex. Make sure it has a backslash in front of it if you mean to match against a literal parenthesis.

Upvotes: 3

escape your parenthesies with \( and \).

private static readonly Regex phoneNumber = new Regex(@"\(\d{3}\)\d{3}-\d{4}");

Upvotes: 4

Related Questions