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
/(?<!^)\+|[^\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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With