gpt4 book ai didi

java - 使用 Java String.replaceAll 的正则表达式

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:29:29 25 4
gpt4 key购买 nike

我希望按如下方式替换 java 字符串值。以下代码无效。

        cleanInst.replaceAll("[<i>]", "");
cleanInst.replaceAll("[</i>]", "");
cleanInst.replaceAll("[//]", "/");
cleanInst.replaceAll("[\bPhysics Dept.\b]", "Physics Department");
cleanInst.replaceAll("[\b/n\b]", ";");
cleanInst.replaceAll("[\bDEPT\b]", "The Department");
cleanInst.replaceAll("[\bDEPT.\b]", "The Department");
cleanInst.replaceAll("[\bThe Dept.\b]", "The Department");
cleanInst.replaceAll("[\bthe dept.\b]", "The Department");
cleanInst.replaceAll("[\bThe Dept\b]", "The Department");
cleanInst.replaceAll("[\bthe dept\b]", "The Department");
cleanInst.replaceAll("[\bDept.\b]", "The Department");
cleanInst.replaceAll("[\bdept.\b]", "The Department");
cleanInst.replaceAll("[\bdept\b]", "The Department");

实现上述替换的最简单方法是什么?

最佳答案

如果这是一个你一直在使用的功能,那就有问题了。每次调用都会再次编译每个正则表达式。最好将它们创建为常量。你可以有这样的东西。

private static final Pattern[] patterns = {
Pattern.compile("</?i>"),
Pattern.compile("//"),
// Others
};

private static final String[] replacements = {
"",
"/",
// Others
};

public static String cleanString(String str) {
for (int i = 0; i < patterns.length; i++) {
str = patterns[i].matcher(str).replaceAll(replacements[i]);
}
return str;
}

关于java - 使用 Java String.replaceAll 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16866077/

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