我有一个Dictionary对象,它由几个条目组成:

record Dictionary(String key, String value, String other) {};

我想用相应的值替换给定的Stringmy 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());
    }
}

Output:

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相关问答推荐

那么比较似乎不是词典学的,尽管doctor 这么说

int Array Stream System. out. print方法在打印Java8时在末尾添加% sign

为什么一个java函数会返回一个作为参数传递给它的对象?

AlarmManager没有在正确的时间发送alert

为什么我要创建一个单独的互斥体/锁对象?

为什么我的ArrayList索引的索引总是返回-1?

';com.itextpdf.ext.html.WebColors已弃用

GSON期间的Java类型擦除

Bean定义不是从Spring ApplationConext.xml文件加载的

如何从错误通道回复网关,使其不会挂起

无法使用ApacheSpark依赖项构建JavaFX应用程序

我如何知道MediaDiscoverer何时完成发现介质?

在Oracle JDBC连接中,连接失效和身份验证失效是什么意思?

在Spring Boot应用程序中,server.port=0的默认端口范围是多少?

错误:不兼容的类型:Double不能转换为Float

Oracle中从JSON中提取和插入数据

协同 routine 似乎并不比JVM线程占用更少的资源

如何正确使用java.time类?

当我将鼠标悬停在javafxTextArea上时,如何更改鼠标光标?

如何组合Mono和Flux