gpt4 book ai didi

java - 无限循环 matcher.find()

转载 作者:行者123 更新时间:2023-11-29 05:33:04 25 4
gpt4 key购买 nike

我正在尝试从 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/

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