简体   繁体   English

测试字符串中的 n 个数字

[英]Test for n digits in a string

I am trying to solve 'JavaScript Algorithms and Data Structures Projects: Telephone Number Validator' @freeCodeCamp.我正在尝试解决“JavaScript 算法和数据结构项目:电话号码验证器”@freeCodeCamp。

I need to test if string contains 10 digits and what I've come up with returns false and I don't understand why.我需要测试字符串是否包含 10 位数字,我想出的结果返回 false,我不明白为什么。

console.log(/\d{10}/g.test("555-555-5555"))

Here \\d{10} means ten consecutive digits , not "ten digits with whatever in the middle, that's cool".这里的\\d{10}表示十个连续的数字,而不是“中间有任何数字的十个数字,这很酷”。

If want just 10 digits, you may want to strip non-digit data first:如果只需要 10 位数字,您可能需要先去除非数字数据:

let number = "555-555-5555";

// Remove all non-digit values (\D) which leaves only digits
let digits = number.replace(/\D/g, '').length;

If you want to do this with a single regular expression, you can use:如果要使用单个正则表达式执行此操作,可以使用:

 console.log(/^(?:\\D*\\d){10}\\D*$/g.test("555-555-5555")) console.log(/^(?:\\D*\\d){10}\\D*$/g.test("555-555-55555"))

requiring the input to be composed of exactly 10 digits in addition to any number of other non-digit characters - but replacing non-digits with the empty string first would be a more intuitive and readable solution.除了任意数量的其他非数字字符外,要求输入必须由 10 位数字组成 - 但首先用空字符串替换非数字将是一个更直观和可读的解决方案。

It seems that your idea is correct, but this specific challenge has so many options for dashes [-] and parentheses [()] as inputs that there is a more efficient way to pass this.看来你的想法是正确的,但是这个特定的挑战有很多选项,破折号 [-] 和括号 [()] 作为输入,有一种更有效的方法来传递它。

function telephoneCheck(str) {
  let phoneRegex = /^(1\s?)?(\d{3}|\(\d{3}\))[\s\-]?\d{3}[\s\-]?\d{4}$/
  return phoneRegex.test(str);
}

The above is a way to complete the challenge in a single line of Regex, which can save you (or anyone else reading this in the future) a lot of time and space!以上是在一行正则表达式中完成挑战的方法,可以为您(或将来阅读本文的任何其他人)节省大量时间和空间! Cheers干杯

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

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