【问题标题】:Regex to parse phone numbers in text document with java正则表达式用java解析文本文档中的电话号码
【发布时间】:2013-08-03 20:16:38
【问题描述】:

我正在尝试使用正则表达式来查找 (xxx) xxx-xxxx 形式的电话号码,这些电话号码都在带有混乱 html 的文本文档中。

文本文件的行如下:

  <div style="font-weight:bold;">
  <div>
   <strong>Main Phone:
   <span style="font-weight:normal;">(713) 555-9539&nbsp;&nbsp;&nbsp;&nbsp;
   <strong>Main Fax:
   <span style="font-weight:normal;">(713) 555-9541&nbsp;&nbsp;&nbsp;&nbsp;
   <strong>Toll Free:
   <span style="font-weight:normal;">(888) 555-9539

我的代码包含:

Pattern p = Pattern.compile("\\(\\d{3}\\)\\s\\d{3}-\\d{4}");
Matcher m = p.matcher(line); //from buffered reader, reading 1 line at a time

if (m.matches()) {
     stringArray.add(line);
}

问题是当我将简单的东西放入模式中进行编译时,它仍然没有返回任何内容。如果它甚至不识别像 \d 这样的东西,我要如何获得电话号码?例如:

Pattern p = Pattern.compile("\\d+"); //Returns nothing
Pattern p = Pattern.compile("\\d");  //Returns nothing
Pattern p = Pattern.compile("\\s+"); //Returns lines
Pattern p = Pattern.compile("\\D");  //Returns lines

这真的让我很困惑,如果有任何帮助,我们将不胜感激。

【问题讨论】:

    标签: java html regex


    【解决方案1】:

    使用Matcher#find() 而不是matches(),它会尝试将整行匹配为电话号码。 find() 也会搜索并返回 true 以查找子字符串匹配项。

    Matcher m = p.matcher(line);
    

    此外,上面的行表明您正在循环中再次创建相同的PatternMatcher。那效率不高。将 Pattern 移到循环之外,然后在不同的行上重置和重用相同的 Matcher

    Pattern p = Pattern.compile("\\(\\d{3}\\)\\s\\d{3}-\\d{4}");
    
    Matcher m = null;
    String line = reader.readLine();
    if (line != null && (m = p.matcher(line)).find()) {
        stringArray.add(line);
    }
    
    while ((line = reader.readLine()) != null) {
      m.reset(line);
      if (m.find()) {
        stringArray.add(line);
      }
    }
    

    【讨论】:

    • 这就是解决方案。感谢您阐明 find() 和 matches() 之间的区别。
    【解决方案2】:

    或者代替regexp你可以使用谷歌库-libphonenumber,如下

        Set<String> phones = new HashSet<>();
        PhoneNumberUtil util = PhoneNumberUtil.getInstance();
    
        Iterator<PhoneNumberMatch> iterator = util.findNumbers(source, null).iterator();
    
        while (iterator.hasNext()) {
            phones.add(iterator.next().rawString());
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-02
      • 2019-05-23
      • 1970-01-01
      • 2018-12-02
      • 2017-04-09
      • 1970-01-01
      • 2017-09-23
      • 2014-02-15
      相关资源
      最近更新 更多