我有一个 Dictionary
对象,它包含几个条目:
record Dictionary(String key, String value, String other) {};
我想用相应的值替换给定 String
my a 中的单词,这些单词在其中一个词典中作为“键”出现。我可以这样实现它,但我想,一定有更好的方法来做到这一点。
一个例子:
> Input: One <sup>a</sup> Two <sup>b</sup> Three <sup>D</sup> Four
> Output: One [a-value] Two [b-value] Three [D] Four
需要改进的代码:
public class ReplaceStringWithDictionaryEntries {
public static void main(String[] args) {
List<Dictionary> dictionary = List.of(new Dictionary("a", "a-value", "a-other"),
new Dictionary("b", "b-value", "b-other"));
String theText = "One <sup>a</sup> Two <sup>b</sup> Three <sup>D</sup> Four";
Matcher matcher = Pattern.compile("<sup>([A-Za-z]+)</sup>").matcher(theText);
StringBuilder sb = new StringBuilder();
int matchLast = 0;
while (matcher.find()) {
sb.append(theText, matchLast, matcher.start());
Optional<Dictionary> dict = dictionary.stream().filter(f -> f.key().equals(matcher.group(1))).findFirst();
if (dict.isPresent()) {
sb.append("[").append(dict.get().value()).append("]");
} else {
sb.append("[").append(matcher.group(1)).append("]");
}
matchLast = matcher.end();
}
if (matchLast != 0) {
sb.append(theText.substring(matchLast));
}
System.out.println("Result: " + sb.toString());
}
}
输出:
Result: One [a-value] Two [b-value] Three [D] Four
你有更优雅的方式来做到这一点吗?
最佳答案
从 Java 9 开始,Matcher#replaceAll
可以接受回调函数以返回每个匹配值的替换值。
String result = Pattern.compile("<sup>([A-Za-z]+)</sup>").matcher(theText)
.replaceAll(mr -> "[" + dictionary.stream().filter(f -> f.key().equals(mr.group(1)))
.findFirst().map(Dictionary::value)
.orElse(mr.group(1)) + "]");
关于Java-Stream 和 Optional - 查找与流元素匹配的值或提供默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73671841/