【问题标题】:In javascript, i need a Regular expression to match balanced parentheses in a phone number /^([1]{0,1})\s?\(?\d{3}\)?[-\s]?\d{3}[-\s]?\d{4}$/在javascript中,我需要一个正则表达式来匹配电话号码中的平衡括号 /^([1]{0,1})\s?\(?\d{3}\)?[-\s]?\d {3}[-\s]?\d{4}$/
【发布时间】:2021-10-27 14:45:14
【问题描述】:

电话号码可能有:

  • 一个起始 "1" 是可选的
  • 然后是"Space",这是可选的
  • 然后是"(",这是可选的
  • 然后是 3 位数,然后是 ")" 然后
  • "space""No space""-"
  • 再次"(",这是可选的
  • 然后是 3 位数字,然后是 ")"
  • 然后空格或无空格或"-"
  • 然后是"(",这是可选的
  • 然后是 3 位数字

例如:5555555555555 555 5555555-555-5555(555)-(555)-5555

例如:1 555 555 55551555 555 55551555-555-55551-555-555-55551 (555) (555) 5555


/^([1]{0,1})\s?\(?\d{3}\)?[-\s]?\d{3}[-\s]?\d{4}$/

上述正则表达式在上述所有方面都可以正常工作,但在以下示例中失败,这意味着 如果我只使用了左括号而没有右括号,那么我找不到它还返回true,这不应该!请帮忙

例如:1 (555-555-5555 例如:555) 555 5555

【问题讨论】:

标签: javascript asp.net .net regex


【解决方案1】:

正则表达式

/^1?[- ]?(?:(?:\d{3}|\(\d{3}\))[- ]?){2}\d{4}$/

完全符合你的例子

现场示例:https://regexr.com/64iu7

【讨论】:

    【解决方案2】:

    让 Javascript 根据有效格式列表自动创建一个正则表达式,将处理电话号码的任何格式,只要该号码在有效格式列表中。

    上下文和测试平台中的“通过脚本自动创建正则表达式”:

    const validFormat = ["5555555555", "555 555 5555", "555-555-5555"
    , "(555)-(555)-5555" , "1 555 555 5555", "1555 555 5555"
    , "1555-555-5555", "1-555-555-5555", "1 (555) (555) 5555"];
    
    let uniqueListTmp = new Set();
    
    for(const s of validFormat) {
        let tmp1 = s.replace(/\d/g, "\\d");
        let tmp2 = tmp1.replace(/([\(|\)])/g, "\\$1");
        uniqueListTmp.add(tmp2);
    }
    
    let regexAsString = "^("; 
    for(const s of uniqueListTmp) {
        regexAsString += s + "|";
    }
    
    regexAsString = regexAsString.replace(/\|$/, ")$")
    const regex = new RegExp(regexAsString);
    
    const invalidInput = ["555", "5 5 5", "5-5-5"];
    const validAndInvalidInput = validFormat.concat(invalidInput);
    
    for(const s of validAndInvalidInput) {
        console.log(s, ' -> ', regex.test(s));
    }
    

    控制台输出:

    5555555555  ->  true
    555 555 5555  ->  true
    555-555-5555  ->  true
    (555)-(555)-5555  ->  true
    1 555 555 5555  ->  true
    1555 555 5555  ->  true
    1555-555-5555  ->  true
    1-555-555-5555  ->  true
    1 (555) (555) 5555  ->  true
    555  ->  false
    5 5 5  ->  false
    5-5-5  ->  false
    

    【讨论】:

      猜你喜欢
      • 2018-03-24
      • 1970-01-01
      • 2013-09-02
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      • 2013-10-01
      • 1970-01-01
      相关资源
      最近更新 更多