-1

I have a regex \(?\+\(?49?\)?[ ()]?([- ()]?\d[- ()]?){11}

This correctly matches German phone code like

  1. +491739341284
  2. +49 1739341284
  3. (+49) 1739341284
  4. +49 17 39 34 12 84
  5. +49 (1739) 34 12 84
  6. +(49) (1739) 34 12 84
  7. +49 (1739) 34-12-84

but fails to match 0049 (1739) 34-12-84. I need to adjust the regular expression so that it can match numbers with 0049 as well. can anyone help me with the regex?

Ayub Jamal
  • 135
  • 10
  • What have you tried so far? How much of the REGEx you have do you understand? What could be the problem? – helle Jul 20 '22 at 20:07
  • so I tried this basic ```((\+49)?(0049)?)([0-9]{11})```, but it wont removed the spaces, so stack overflow it and got ```\(?\+\(?49?\)?[ ()]?([- ()]?\d[- ()]?){11}``` this one, now I'm finding it hard to add (0049) thing in this one – Ayub Jamal Jul 20 '22 at 20:13
  • tried this ```\(?\+\(?49?(0049)?[ ()]?([- ()]?\d[- ()]?){11}``` but didn't worked – Ayub Jamal Jul 20 '22 at 20:14
  • Note that your pattern does not match `+(49) (1739) 34 12 84` Is that the expected? See https://regex101.com/r/ij49Hv/1 – The fourth bird Jul 20 '22 at 20:34
  • yeah you are right, it should match – Ayub Jamal Jul 20 '22 at 20:54

2 Answers2

0

Try this one:

\(?\+|0{0,2}\(?49\)?[ ()]*[ \d]+[ ()]*[ -]*\d{2}[ -]*\d{2}[ -]*\d{2}

https://regex101.com/r/CHjNBV/1

However, it's better to make it accept only +49 or 0049, and throw the error message in case the number fails validation. Because if someday you will require to extend the format - it will require making the regex much more complicated.

Djanym
  • 332
  • 1
  • 4
  • 13
0

If you want to match the variations in the question, you might use a pattern like:

^(?:\+?(?:00)?(?:49|\(49\))|\(\+49\))(?: *\(\d{4}\)|(?: ?\d){4})? *\d\d(?:[ -]?\d\d){2}$

Explanation

  • ^ Start of string
  • (?: Non capture group
    • \+? Match an optional +
    • (?:00)? Optionally match 2 zeroes
    • (?:49|\(49\)) Match 49 or (49)
    • | Or
    • \(\+49\) Match (+49)
  • ) Close non capture gruop
  • (?: Non capture group
    • * Match optional spaces
    • \(\d{4}\) Match ( 4 digits and )
    • | Or
    • (?: ?\d){4} Repeat 4 times matching an optional space and a digit
  • )? Close non capture group and make it optional
  • * Match optional spaces
  • \d\d Match 2 digits
  • (?:[ -]?\d\d){2} Repeat 2 times matching either a space or - followed by 2 digits
  • $ End of string

Regex demo

Or a bit broader variation matching the 49 prefix variants, followed by matching 10 digits allowing optional repetitions of what is in the character class [ ()-]* in between the digits.

^(?:\+?(?:00)?(?:49|\(49\))|\(\+49\))(?:[ ()-]*\d){10}$

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70