gpt4 book ai didi

java - 如何使用 Matcher 单独替换每个组?

转载 作者:行者123 更新时间:2023-11-30 04:00:50 25 4
gpt4 key购买 nike

我发现的所有例子都是针对人们有一些正则表达式模式的情况已搜索并需要用某个特定值或搜索字符串中已知数量的组替换找到的所有组。

但就我而言,我需要根据找到的值更改每个组,如何更改每个更改的结果值?

这是我已经/尝试过的:

 Pattern pattern = Pattern.compile(DEFINITION_WITH_OR);
Matcher matcher = pattern.matcher(s);
StringBuffer sb = new StringBuffer();
while (matcher.find()){

String ss = matcher.group();

/*Some string manupilation*/

// matcher.appendReplacement(sb, bestMatchedDefinition);
// matcher.appendReplacement(sb,Matcher.quoteReplacement(ss));
// s = s.replace(s.substring(matcher.start(),matcher.end()),ss);

}

我想要做的是遍历找到的所有组,对找到的组执行一些操作,然后仅编辑该组,组的内容和数量在运行之前未知。

到目前为止我的所有尝试要么改变了一切,要么根本没有改变,有什么建议吗?

我对字符串所做的是将其分割为 | ,得到最短的部分,然后去掉大括号:输入字符串示例:注意:以下输入字符串是一个简化,用于显示我的最终结果应该是什么,完整的字符串有很多更烦人的字符,我使用 DEFINITION_WITH_OR 清除了这些字符。图案

 a commissioned general officer in the United States Army,
[[United States Marine Corps|Marine Corps]],
or [[United States Air Force|Air Force]] superior to a lieutenant general.
A general is equal in rank or grade to a four star admiral. In the US Army,
a general is junior to a general of the army. In the US Marine Corps,
a general is the highest rank of commissioned officer. In the US Air Force,
a general is junior to a general of the air force.

应输出为:

 a commissioned general officer in the United States Army,
Marine Corps,
or Air Force superior to a lieutenant general.
A general is equal in rank or grade to a four star admiral. In the US Army,
a general is junior to a general of the army. In the US Marine Corps,
a general is the highest rank of commissioned officer. In the US Air Force,
a general is junior to a general of the air force.

注意空军海军陆战队位。

最佳答案

    String source = "a commissioned general officer in the United States Army, "
+ "[[United States Marine Corps|Marine Corps]], "
+ "or [[United States Air Force|Air Force]] superior to a lieutenant general.";
Pattern pattern = Pattern.compile("\\[\\[(.*?)\\]\\]");
Matcher m = pattern.matcher(source);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String[] terms = m.group(1).split("\\|");
String shortestTerm = null;
for (String term : terms) {
if (shortestTerm == null || term.length() < shortestTerm.length()) {
shortestTerm = term;
}
}
m.appendReplacement(sb, shortestTerm);
}
m.appendTail(sb);
String target = sb.toString();
System.out.println(target);

注意虚假的反斜杠。 ".*?" 采用最短序列匹配。

关于java - 如何使用 Matcher 单独替换每个组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22016401/

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