【问题标题】:Regex to remove chars from phone numbers正则表达式从电话号码中删除字符
【发布时间】:2015-02-19 13:15:32
【问题描述】:

我们需要在 C# 中使用 Regex.Replace() 从电话号码中删除字符。允许的字符是 +(仅第一个字符)和 [0-9]。应该过滤其他任何内容。

替换所有非数字都可以正常工作,但我们如何允许 + 仅作为第一个字符?

我们的正则表达式:

[^+0-9]+

在这个数字上:+41 456-7891+23 它将删除空格和连字符,但不会删除 23 前面的 +

知道如何解决这个问题吗?

【问题讨论】:

  • 你用什么语言写这个?许多像 Ruby 这样的语言都有内置的方法来去除不需要完整正则表达式的字符串
  • 请指定使用的语言。
  • 要去掉所有非数字但留下+,如果它是第一个字符,可以使用anchors:^[^\d+]|\b\D+并替换为空。见test at regex101.com

标签: c# regex


【解决方案1】:

使用下面的正则表达式,然后将匹配的字符替换为\1$1

^(\+)|\D

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

DEMO

并且不要忘记在使用上述正则表达式时添加多行修饰符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

鲁比:

> '+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# 版本感兴趣 :)
  • 我非常感谢其他版本!尤其是 PHP 的!
【解决方案2】:

这是用 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);
  };

【讨论】:

  • 相同的正则表达式出现在接受的答案中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-23
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多