I have a regex
\(?\ \(?49?\)?[ ()]?([- ()]?\d[- ()]?){11}
This correctly matches German phone code like
- 491739341284
- 49 1739341284
- ( 49) 1739341284
- 49 17 39 34 12 84
- 49 (1739) 34 12 84
- (49) (1739) 34 12 84
- 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?
CodePudding user response:
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.
CodePudding user response:
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\dMatch 2 digits(?:[ -]?\d\d){2}Repeat 2 times matching either a space or-followed by 2 digits$End of string
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}$
