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