Search code examples
regexrubyregex-group

Regex fomat phone (+00) 000 000 00 00 | (+00) 000-000-00-00 ​


Hello i want found a regular expression that accomplish this two formats:

(+00) 000 000 00 00

(+00) 000-000-00-00 ​

i am try this (?:\+\s*\d{2}[\s-]*)?(?:\d[-\s]*){10}/ but its no working how i wanted, can you help me? i am using ruby i am probing this regex with https://rubular.com/.


Solution

  • You can use

    /\A\(\+\d{2}\) \d{3}([ -])\d{3}\1\d{2}\1\d{2}\z/
    /\A\(\+\d{2}\)\s\d{3}([\s-])\d{3}\1\d{2}\1\d{2}\z/
    

    See the Rubular demo. Note that \s matches spaces, tabs, line breaks, any whitespace.

    More details

    • \A - start of string
    • \(\+ - (+ substring
    • \d{2} - two digits
    • \) - a ) char
    • \s - a whitespace
    • \d{3} - three digits
    • ([\s-]) - Group 1: a whitespace or a - char
    • \d{3} - three digits
    • \1 - backreference to Group 1: same value as in Group 1
    • \d{2} - two digits
    • \1 - backreference to Group 1: same value as in Group 1
    • \d{2} - two digits
    • \z - end of string.