Java 如何用arraylist中的多个匹配项替换字符串?
假设我有一个字符串,比如Java 如何用arraylist中的多个匹配项替换字符串?,java,Java,假设我有一个字符串,比如stringx“这是一个示例字符串!” 我试图从数组中找到像[This,an,string]这样的所有单词,如果找到匹配项,则将它们全部替换为*inx 到目前为止,我已经尝试了类似的变化: List<String> index = new ArrayList(); index.add("This"); index.add("an"); index.add("example"); String words = index.toString().repla
stringx“这是一个示例字符串!”代码>
我试图从数组中找到像[This,an,string]
这样的所有单词,如果找到匹配项,则将它们全部替换为*inx
到目前为止,我已经尝试了类似的变化:
List<String> index = new ArrayList();
index.add("This");
index.add("an");
index.add("example");
String words = index.toString().replaceFirst("\\[", "").replaceFirst("\\]", "");
Boolean result = x.contains(words);
if (result == true){
String newMessage = x.replaceAll("[words.split(\\W+)]", "*");
}
List index=new ArrayList();
索引。添加(“本”);
索引。添加(“an”);
添加索引(“示例”);
String words=index.toString().replaceFirst(\\[“,”).replaceFirst(\\[“,”);
布尔结果=x.contains(字);
如果(结果==真){
字符串newMessage=x.replaceAll(“[words.split(\\W+)”,“*”);
}
这类操作可以正常工作,但要求字符串必须按照与字符串的显示顺序包含This,an,string
。您可以使用一个简单的for循环:
List<String> index = // ...
String message = "This is an example string!";
for (String word : index) {
message = message.replace(word, "*");
}
列表索引=/。。。
String message=“这是一个示例字符串!”;
for(字符串字:索引){
message=message.replace(单词“*”);
}
反复浏览列表中的每个单词。将x
中的结果替换为*
,将结果分配回x
。大概
List<String> index = Arrays.asList("This", "an", "example");
String x = "This is an example string!";
for (String str : index) {
x = x.replace(str, "*");
}
System.out.println(x);
此方法用于替换第一个单词This,但其余单词保持不变,“*是一个示例字符串!”。谢谢分享。改变Array.asList=。。。要从YAML文件中提取?
* is * * string!