0
"^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4})|((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{5})|((\+44\s?\d{5}|\(?0\d{5}\)?)\s?\d{5})|((\+44\s?\d{5}|\(?0\d{5}\)?)\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$";

I use the above pattern to validate UK telephone number. It's working in JavaScript (client side). but its not working in Java code (server side). The error message says invalid escape sequence.

1
  • I'm going to deploy a favourite quote here - "You think that you need a regex to solve your problem, so you write one. Now you have 2 problems." The point being that perhaps when regexes get this big and ugly, it's time to look at solving your problem another way. Commented Apr 10, 2012 at 8:20

2 Answers 2

6

You need to replace all your \ with \\ Having said that, it seems like your regex is a bit complicated for a phone-number? I see that the country-code for GB (+44) is included quite a few times, so I guess you could be able to say that only once:

^(\+44)?(...)

And the rest of the regex where the elipsis are.

Another idea to make this clearer is to break this regex into several ones for each case like:

if (matches case 1) return true; // example of case one
if (matches case 2) return true; // example of case two
if (matches case 3) return true; // example of case tree
...
return false;

In my opinion this code would be much simpler to maintain.

Sign up to request clarification or add additional context in comments.

Comments

3

That's because Java simply doesn't accept \ in a string (since \ is unescaped). Escape \ with \\ instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.