简体   繁体   中英

Regex to remove chars from phone numbers

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?

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

This is written in React. Should be easy enough converting it to VanillaJS;) It replaces any non-numerical values with nothing, just keeping the number (and the + sign):)

    //function that is used to set the number amount that the user wants to convert
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    //this regex cleans any non-numerical values from the input
    let RegEx = /^(\+)|[^\d\n]/;
    const cleanedInput = e.currentTarget.value.replace(RegEx, '');

    //sets the amount the user wants to convert to the cleanedInput from the RegEx
    setConvertAmount(cleanedInput);
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM