[英]How to define different regex for the first character, and the rest of the string?
I want to validate and process a string, which should be a telephone number. 我想验证并处理一个字符串,该字符串应该是电话号码。 For the first character, numbers and + is accepted, for the rest, just numbers.
对于第一个字符,数字和+被接受,对于其余字符,仅数字。
I have the solution to accept + and numbers, but just for the whole string: 我有接受+和数字的解决方案,但只针对整个字符串:
console.log("asd242++asf43+234".replace(/[^+\\d]/g, ""))
But suffering from defining different check for the first character, and the rest. 但是,在为第一个字符和其余字符定义不同的检查时会遇到麻烦。
You can use the following: 您可以使用以下内容:
([^+\d]|(?!^)\+)
It matches everything that is not a digit nor a +
and doesn't match +
at the beginning of the string! 它匹配所有不是数字也不是
+
且不匹配+
的内容。
So your test log would look like this: 因此,您的测试日志如下所示:
console.log("+asd242++asf43+234".replace(/([^+\\d]|(?!^)\\+)/g, ""))
(i added a +
to the beginning to show it handles this correctly!) (我在开头添加了一个
+
,以表明它可以正确处理此问题!)
See a Demo that shows it matches all your cases! 观看演示 ,演示它与您的所有案例都匹配!
What I understood you want to validate +numbers
. 据我了解,您想验证
+numbers
。 You should use ^
and $
in start of end of your regex. 您应在正则表达式的末尾使用
^
和$
。 I think following regex will work if i am not wrong. 我认为,如果我没有记错,遵循正则表达式将起作用。
/^\+[0-9]+$/
Try this one: /^[+]?[0-9]+$/g
试试这个:
/^[+]?[0-9]+$/g
^ - start of string ^-字符串的开头
[+]? [+]? - single optional + character
-单个可选+字符
[0-9]+ - one or more digit [0-9] +-一位或多位数字
$ - end of string $-字符串结尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.