我正在尝试从 html 页面获取地址。我有一个正则表达式,从中我可以找到州、城市和电话号码。
String linearray[] = newdoc.split("\n");
int count = 0;
System.out.println(linearray.length);
while(count<linearray.length)
{
System.out.println(count);
Pattern pattern = Pattern.compile("(.*?)(\\d{1,4}(\\s*\\w*)*)(\\s*)(CA|AZ|NY)(\\s*)(\\(?[1-9]\\d{2}\\)?\\s*\\d{3}\\d{4})?(.*?)");
Matcher matcher = pattern.matcher(linearray[count].trim());
while (matcher.find()) {
String state = matcher.group(5);
String city = matcher.group(2);
String phone = matcher.group(7);
System.out.println("state "+state+" city "+city+" phone "+phone+" ");
}
count++;
}
当我尝试运行这段代码时,它进入了无限循环。 谁能帮我解决这个问题?
编辑:
当 linearray[count]==“Bombay Garden Newark SanMateo SantaClara © 2011 Bombay Garden All Rights Reserved”
时,我的代码卡在 while(matcher.find() )
。知道为什么它会卡在那里吗?当我跳过该行(通过使用 continue)时,代码终止得很好!
最佳答案
您的正则表达式导致“catastrophic backtracking”,使其过于复杂而无法完成。
考虑将正则表达式重写为更多 possessive .
关于java - 无限循环 matcher.find(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20448125/