Dren Dren - 4 months ago 18
Perl Question

reformat numbers using regex

I have a file that contains any of the following number format

123.456.7890
(123)456.7890
(123).456.7890
123-456-7890
(123)-456-7890
(123)456-7890


Is it possible to use regex substitution so that the final output number will always be on a format (123)456-7890

Answer

Yes, it is:

s/\(?(\d\d\d)\)?[-.]?(\d\d\d)[-.]?(\d\d\d\d)/($1)$2-$3/g

I should mention that the above will also parse the following two:

123)456.7890
(123456.7890
Comments