Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trim phone number with regex

Tags:

regex

Probably an easy regex question.

How do I remove all non-digts except leading + from a phone number?

i.e.

012-3456 => 0123456
+1 (234) 56789 => +123456789

like image 404
adrianm Avatar asked Dec 05 '22 02:12

adrianm


1 Answers

/(?<!^)\+|[^\d+]+//g

will remove all non-numbers and leave a leading + alone. Note that leading whitespace will cause the "leave + alone" bit to fail. In .NET languages, this can be worked into the regex, in others you should strip whitespace first before passing the string to this regex.

Explanation:

(?<!^)\+: Match a + unless it's at the start of the string. (In .NET, use (?<!^\s*)\+ to allow for leading whitespace).

| or

[^\d+]+: match any run of characters that are neither numbers nor +.

Before (using (?<!^\s*)\+|[^\d+]+):

+49 (123) 234 5678
  +1 (555) 234-5678
+7 (23) 45/6789+10
(0123) 345/5678, ext. 666

After:

+491232345678
+15552345678
+72345678910
01233455678666
like image 97
Tim Pietzcker Avatar answered Dec 20 '22 15:12

Tim Pietzcker