0

I'm trying to write a regex to allow phone country codes in this format: +NNNN, where N is a number. I tried with this one but it didn't work:

/^\\+|[0-9]+$/

What is wrong?

2
  • 1
    I think its allowing more than 4 numbers. What about /^\\+[0-9]{4}$/ ? Commented Mar 12, 2014 at 14:36
  • Well, it's JavaScript so obviously this wouldn't work due to the improper escaping. Commented Mar 12, 2014 at 14:44

3 Answers 3

1

What about that?

/^\+[0-9]{1,4}$/
Sign up to request clarification or add additional context in comments.

4 Comments

Won't this match +9 or +99, which is not what the OP asks?
I have a extra problem, I should allow +NNNN but also NNNNN in this way only the first one is allowed, how I can fix that? I tough for that reason I had the | pipe
To allow '+' being optional, add a '?' symbol after the plus sign: /^\+?[0-9]{1,4}$/
Also, the pipe symbol is used to match between several alternatives, but I don't think this is going to help you with that.
1

Why do you use pipe inside your regex. Just remove it. Using pipe actually bisecting your regex into two.

/^\\+[0-9]+$/

Comments

1

Regex: /^\+[0-9]{4}$/

Matches: +9999

  1. \+ matches + literally.
  2. [0-9]{4} matches 4 occurrences of a digit.

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.