2013-08-03 89 views
3

我想用正则表达式来查找电话号码在窗体(xxx)xxx-xxxx里面都是一个文本文档与凌乱的HTML。正则表达式来解析与java文本文件中的电话号码

文本文件有像行:

<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 

这真是令我困惑,任何帮助,将不胜感激。

回答

3

使用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); 
    } 
} 
+0

这是解决方案。感谢您澄清find()和matches()之间的区别。 –

2

你可以使用谷歌图书馆 - 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()); 
    } 
+0

谢谢@Khozzy这是伟大的工作。很有帮助 – srinivas