从电话号码中删除字符的正则表达式

5
我们需要使用Regex.Replace()在C#中删除电话号码中的字符。允许的字符是+(仅限第一个字符)和[0-9]。任何其他字符都应该被过滤掉。虽然替换所有非数字的方法很好用,但我们如何只允许+作为第一个字符呢?我们的正则表达式:
[^+0-9]+

在这个号码:+41 456-7891+23 中,需要去除空格和连字符,但不要去除23前面的+
有什么解决办法吗?

1
你用什么语言编写这个?很多语言,比如Ruby,都有内置的方法可以去除字符串中不需要完整正则表达式的字符。 - Devon Parsons
请指定正在使用的编程语言。 - TheLostMind
为了去除所有非数字字符,但是保留加号(如果它是第一个字符),可以使用锚点:^[^\d+]|\b\D+ 并替换为空。请参见 regex101.com 上的测试 - Jonny 5
2个回答

19
使用以下正则表达式,然后将匹配的字符替换为 \1$1
^(\+)|\D
OR
^(\+)|[^\d\n]

演示

使用上述正则表达式时,请不要忘记添加多行修饰符m

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"));

基本的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

很不错,但我猜Mark只对C#版本感兴趣 :) - Wiktor Stribiżew
1
我非常感激其他版本!特别是 PHP 版本! - cbloss793

-1

这是用React编写的。将其转换为VanillaJS应该很容易 ;) 它将任何非数字值替换为无,只保留数字(和加号):)

    //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);
  };

相同的正则表达式出现在被接受的答案中。 - miken32

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接