Java-Stream 和 Optional - 查找与流元素匹配的值或提供默认值

标签 java regex string java-stream option-type

我有一个 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/

相关文章:

java - 无法解析方法 setText(java.lang.String)

mysql - 如何获取除括号中的所有匹配词?正则表达式/Mysql

regex - 如何在lua中通过正则表达式重复匹配多个表达式

java - 如何在没有任何复杂路线的情况下改变字符串?

Python 朱利叶斯·凯撒密码程序

java - 在 Java 中从 Internet 获取数据

java - 如何检查 TreeMap<String, ArrayList<String>> 是否包含值? java 语

c# - 特殊字符的正则表达式

javascript - 从基于文本的内容中删除某些 html 标签

java - ListSelectionListener 调用 setSelected 方法时不会触发事件