Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to remove chars from phone numbers

Tags:

c#

regex

We need to remove chars from phone numbers using Regex.Replace() in C#. Allowed chars are + (only the first char) and [0-9]. Anything else should be filtered.

Replacing everything non numeric works fine, but how can we allow + only on as the first char?

Our Regex:

[^+0-9]+

On this number: +41 456-7891+23 it would remove whitespace and hyphens but not the + in front of 23.

Any idea how this can be solved?

like image 485
Mark Lowe Avatar asked Dec 08 '22 04:12

Mark Lowe


1 Answers

Use the below regex and then replace the matched characters with \1 or $1.

^(\+)|\D

OR

^(\+)|[^\d\n]

DEMO

And don't forget to add multi-line modifier m while using the above regex.

Javascript:

> '+41 456-7891+23'.replace(/^(\+)|\D/g, "$1")
'+41456789123'

PHP:

$str = '+41 456-7891+23';
echo preg_replace('~^(\+)|\D~', '\1', $str);

R:

> gsub("^(\\+)|\\D", "\\1", '+41 456-7891+23')
[1] "+41456789123"

C#

string result = Regex.Replace('+41 456-7891+23', @"^(\+)|\D", "$1");

Java

System.out.println("+41 456-7891+23".replaceAll("^(\\+)|\\D", "$1"));

Basic sed

$ echo '+41 456-7891+23' | sed 's/^\(+\)\|[^0-9]/\1/g'
+41456789123

Gnu sed

$ echo '+41 456-7891+23' | sed -r 's/^(\+)|[^0-9]/\1/g'
+41456789123

Ruby:

> '+41 456-7891+23'.gsub(/^(\+)|\D/m, '\1')
=> "+41456789123"

Python

>>> re.sub(r'(?<=^\+).*|^[^+].*', lambda m: re.sub(r'\D', '', m.group()), '+41 456-7891+23')
'+41456789123'
>>> regex.sub(r'^(\+)|[^\n\d]', r'\1', '+41 456-7891+23')
'+41456789123'

Perl

$ echo '+41 456-7891+23' | perl -pe 's/^(\+)|[^\d\n]/\1/g'
+41456789123
$ echo '+41 456-7891+23' | perl -pe 's/^\+(*SKIP)(*F)|[^\d\n]/\1/g'
+41456789123
like image 83
Avinash Raj Avatar answered Dec 10 '22 19:12

Avinash Raj