繁体   English   中英

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

[英]Regex to remove chars from phone numbers

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

替换所有非数字的东西都可以正常工作,但是我们怎么能只允许 + 作为第一个字符呢?

我们的正则表达式:

[^+0-9]+

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

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

使用下面的正则表达式,然后用\\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"

蟒蛇

>>> 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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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