gpt4 book ai didi

java - 正则表达式用java解析文本文档中的电话号码

转载 作者:搜寻专家 更新时间:2023-10-31 23:06:00 24 4
gpt4 key购买 nike

我正在尝试使用正则表达式来查找格式为 (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

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

最佳答案

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

关于java - 正则表达式用java解析文本文档中的电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18036897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com