[英]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].我们需要在 C# 中使用 Regex.Replace() 从电话号码中删除字符。允许的字符是 +(仅第一个字符)和 [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.对于这个数字:
+41 456-7891+23
,它会删除空格和连字符,但不会删除 23 前面的+
。
Any idea how this can be solved?知道如何解决这个问题吗?
Use the below regex and then replace the matched characters with \\1
or $1
. 使用下面的正则表达式,然后用
\\1
或$1
替换匹配的字符。
^(\+)|\D
OR 要么
^(\+)|[^\d\n]
And don't forget to add multi-line modifier m
while using the above regex. 并且不要忘记在使用上述正则表达式时添加多行修饰符
m
。
Javascript: 使用Javascript:
> '+41 456-7891+23'.replace(/^(\+)|\D/g, "$1")
'+41456789123'
PHP: PHP:
$str = '+41 456-7891+23';
echo preg_replace('~^(\+)|\D~', '\1', $str);
R : R :
> gsub("^(\\+)|\\D", "\\1", '+41 456-7891+23')
[1] "+41456789123"
C# C#
string result = Regex.Replace('+41 456-7891+23', @"^(\+)|\D", "$1");
Java Java的
System.out.println("+41 456-7891+23".replaceAll("^(\\+)|\\D", "$1"));
Basic sed 基本的sed
$ echo '+41 456-7891+23' | sed 's/^\(+\)\|[^0-9]/\1/g'
+41456789123
Gnu sed 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 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.这是用 React 写的。 Should be easy enough converting it to VanillaJS;) It replaces any non-numerical values with nothing, just keeping the number (and the + sign):)
将它转换为 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.