正则表达式使用Java String.replaceAll

use*_*797 8 java regex string replaceall

我想要替换如下的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");
Run Code Online (Sandbox Code Playgroud)

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

Pau*_*gas 13

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

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;
}
Run Code Online (Sandbox Code Playgroud)


Eng*_*uad 7

cleanInst.replaceAll("[<i>]", "");
Run Code Online (Sandbox Code Playgroud)

应该:

cleanInst = cleanInst.replaceAll("[<i>]", "");
Run Code Online (Sandbox Code Playgroud)

因为String类是不可变的并且不会改变其内部状态,即replaceAll()返回与之不同的新实例cleanInst.