gpt4 book ai didi

java - 用 Java 中字符串中的特殊字符替换单词

转载 作者:行者123 更新时间:2023-12-01 17:00:44 24 4
gpt4 key购买 nike

我正在编写一个方法,该方法应该用“****”替换与列表中的单词匹配的所有单词

字符。到目前为止,我的代码可以工作,但所有特殊字符都被忽略。

我已尝试在表达式中使用 "\\W",但看起来我没有很好地使用它,因此我需要一些帮助。

这是我到目前为止的代码:

        for(int i = 0; i < badWords.size(); i++) {
if (StringUtils.containsIgnoreCase(stringToCheck, badWords.get(i))) {
stringToCheck = stringToCheck.replaceAll("(?i)\\b" + badWords.get(i) + "\\b", "****");
}
}

例如我有单词列表 ['bad', '@$$']。

如果我有一个字符串: "This is bad string with @$$"
我期望此方法返回 "This is **** string with * ***”

请注意,该方法应该注意区分大小写的单词,例如TestTtest 应该处理相同的情况。

最佳答案

我不知道你为什么使用StringUtils你可以直接替换与坏词匹配的词。这段代码对我有用:

public static void main(String[] args) {
ArrayList<String> badWords = new ArrayList<String>();
badWords.add("test");
badWords.add("BadTest");
badWords.add("\\$\\$");
String test = "This is a TeSt and a $$ with Badtest.";
for(int i = 0; i < badWords.size(); i++) {
test = test.replaceAll("(?i)" + badWords.get(i), "****");
}
test = test.replaceAll("\\w*\\*{4}", "****");
System.out.println(test);
}

输出:

This is a **** and a **** with ****.

关于java - 用 Java 中字符串中的特殊字符替换单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27782438/

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