[英]I can't seem to figure out the regular expression
I have the following code.我有以下代码。 I am trying to have the regular express test the phone number for validation.
我正在尝试让常规快递测试电话号码以进行验证。 With the current argument the function should return positive, but it doesn't and I can't figure out why.
使用当前参数,函数应该返回正值,但它没有,我不知道为什么。
function telephoneCheck(str) {
let reg = /^[\d]{0,1}[\w]{0,1}[(]{0,1}[\d]{3}[-)\w]{0,2}[\d]{3}[-\w]{0,1}[\d]/;
return reg.test(str);
}
console.log("function: " + telephoneCheck("1 (555) 555-5555"));
Can anyone see what I am missing?谁能看到我错过了什么?
First, replace all the \\w
(Matches any letter, digit or underscore) with \\s
(Matches any space, tab or newline character).首先,将所有
\\w
(匹配任何字母、数字或下划线)替换为\\s
(匹配任何空格、制表符或换行符)。 I believe you don't won't letter in phone number.我相信你不会在电话号码中写信。 Second, you need to add a quantifier
{0,4}
to the end of your Regex, just like you already did in other positions of the Regex.其次,您需要在正则表达式的末尾添加一个量词
{0,4}
,就像您在正则表达式的其他位置所做的那样。
So the final Regex will be ^[\\d]{0,1}[\\s]{0,1}[(]{0,1}[\\d]{3}[-)\\s]{0,2}[\\d]{3}[-\\s]{0,1}[\\d]{0,4}
所以最终的正则表达式将是
^[\\d]{0,1}[\\s]{0,1}[(]{0,1}[\\d]{3}[-)\\s]{0,2}[\\d]{3}[-\\s]{0,1}[\\d]{0,4}
Because your regex is nonsense.因为你的正则表达式是无稽之谈。
[]
for single group ( [\\d]{0,1}
can be just \\d?
[]
( [\\d]{0,1}
可以只是\\d?
\\w
does not match spaces, just [a-z0-9]
in general case \\w
不匹配空格,一般情况下只是[a-z0-9]
(
but ending )
can be followed by -
or any \\w
(
但结束)
后面可以跟-
或任何\\w
function telephoneCheck(str) { let reg = /^\\d?\\s?\\(?[\\d-]+\\)?\\s?\\d+/; return reg.test(str); } console.log("function: " + telephoneCheck("1 (555) 555-5555"));
\\w
with \\s
for whitespace\\w
替换为\\s
以获取空格\\(
and \\)
\\(
和\\)
[-)\\w]{0,2}
to [-\\)]{0,1}[\\s]{0,1}
unless you want the unorthodox 1 (555)-555-5555 to be true.[-)\\w]{0,2}
更改为[-\\)]{0,1}[\\s]{0,1}
除非您希望非正统的 1 (555)-555-5555 成为真的。[\\d]
should be [\\d]{4}
since you want exactly 4 digits at the end.[\\d]
应该是[\\d]{4}
因为您希望最后有 4 位数字。 function telephoneCheck(str) { let reg = /^[\\d]{0,1}[\\s]{0,1}[\\(]{0,1}[\\d]{3}[-\\)]{0,1}[\\s]{0,1}[\\d]{3}[-\\s]{0,1}[\\d]{4}/; return reg.test(str); } console.log("function: " + telephoneCheck("1 (555)555-5555"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.