gpt4 book ai didi

java - Collections.replaceAll(List list, T oldVal, T newVal) 无法正确使用正则表达式,Java

转载 作者:行者123 更新时间:2023-11-30 05:28:53 25 4
gpt4 key购买 nike

我正在解决必须找到列表中最长的字符串并用该字符串替换所有其他列表项的问题:

The longest string in the list

Inside the given method you should:

1. find the longest string in the list
2. replace all list items with the found string

当我使用正则表达式“\\w+”时,该方法不起作用:

Collections.replaceAll(列表,“\\w+”,longestString);

当我通过在方法参数中指定特定单词来替换它们时 - 一切正常,例如:

Collections.replaceAll(列表,“word”,longestString);

这是为什么呢?我的错误在哪里?

最佳答案

Collections.replaceAll 方法不支持正则表达式。也许你应该使用 List.replaceAll 方法:

list.replaceAll(e -> longestString);
<小时/>

这是工作示例:

// Dummy Values
List<String> list = new ArrayList<>();
list.add("Hey");
list.add("World");
list.add("Bye");
String longestString = "World";

// Replacing every word with `longestString`
list.replaceAll(e -> longestString);

// Printing
System.out.println(list);

输出:

[World, World, World]

关于java - Collections.replaceAll(List<T> list, T oldVal, T newVal) 无法正确使用正则表达式,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57968338/

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