gpt4 book ai didi

Java匹配器和模式: Why does this go on forever

转载 作者:行者123 更新时间:2023-12-01 19:20:51 26 4
gpt4 key购买 nike

//remove multiple with
pat=Pattern.compile("ACCEPT .*?\\.",Pattern.DOTALL);
m=pat.matcher(str);
while(m.find())
{

int start=m.group().indexOf("WITH") +1;
String part=m.group().substring(start);
part=part.replaceAll("WITH", "");
part=m.group().substring(0, start).concat(part);

if(!m.group().equals(part))
{

str=m.replaceFirst(part);

}

}

知道为什么这是一个无限循环吗? m.group 永远不等于part。我不知道为什么。尝试重置但没有任何结果。

最佳答案

我不知道你想要完成什么,但这里有一个错误:

if(!m.group().equals(part))
{
str=m.replaceFirst(part);
}

您正在重新分配 str,而匹配器仍然使用 str 的原始值。字符串是不可变的,如果您在一个位置重新分配变量,它不会更改另一位置的引用(请参阅 this page of the Sun java Tutorial 上的传递引用数据类型参数)。

还有一些更奇怪的事情发生,但也许我没有正确理解你的意思。您在评论中说字符串 以 ACCEPT 开头并以 结尾。点。但这是您正在搜索的唯一内容 Pattern.compile("ACCEPT .*?\\.",Pattern.DOTALL);,并且您也没有捕获任何内容。那为什么一开始还要费力去寻找呢?我以为你知道输入字符串就是这样的。

您真正应该做的是发布一些示例输入以及您想要从中提取的数据。否则没有人能够真正帮助你。

<小时/>

我现在猜测:您似乎想从字符串中删除多个WITH子句。这应该更容易,像这样:

String test =
"ACCEPT pasta "
+ "WITH tomatoes, parmesan cheese, olives "
+ "WITH anchovies WITH tuna WITH more olives.";

System.out.println(
test.replaceAll(
"(ACCEPT.*?WITH.*?)(?:\\s*WITH.*)(\\.)", "$1$2"
)
);

输出:

ACCEPT pasta WITH tomatoes, parmesan cheese, olives.

这是模式,解释如下:

(       // start a capturing group
ACCEPT // search for the literal ACCEPT
.*? // search for the shortest possible matching String
// (so no other WITH can sneak in)
WITH // search for the literal WITH
.*? // search for the shortest possible matching String
// (so no other WITH can sneak in)
) // close the capturing group, we'll refer to this
// group as $1 or matcher.group(1)
(?: // start a non-capturing group
\\s* // search for optional whitespace
WITH // search for the literal WITH
.* // search for anything, greedily
) // close the group, we'll discard this one
( // open another capturing group
\\. // search for a single period
) // close the group, the period is now accessible as $2
<小时/>

根据您更新的要求(删除WITH但保留参数),这里有一个更新的解决方案:

final Matcher matcher =
Pattern.compile("WITH\\s*", Pattern.DOTALL).matcher(test);
final StringBuffer sb = new StringBuffer();
while(matcher.find()){
matcher.appendReplacement(sb, sb.length() == 0
? matcher.group()
: "");
}
matcher.appendTail(sb);
System.out.println(sb.toString());

输出:

ACCEPT pasta WITH tomatoes, parmesan cheese, olives anchovies tuna more olives.

关于Java匹配器和模式: Why does this go on forever,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4335056/

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