簡體   English   中英

正則表達式使用Java String.replaceAll

[英]Regex using Java 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");

實現上述替換的最簡單方法是什么?

如果它是您正在使用的功能,則存在問題。 每次調用都會再次編譯每個正則表達式。 最好將它們創建為常量。 你可以有這樣的東西。

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;
}
cleanInst.replaceAll("[<i>]", "");

應該:

cleanInst = cleanInst.replaceAll("[<i>]", "");

因為String類是不可變的並且不會改變其內部狀態,即replaceAll()返回一個與cleanInst不同的新實例。

您應該閱讀基本的正則表達式教程

在那之前,你試圖做的事情可以這樣做:

cleanInst = cleanInst.replace("//", "/");
cleanInst = cleanInst.replaceAll("</?i>", "");
cleanInst = cleanInst.replaceAll("/n\\b", ";")
cleanInst = cleanInst.replaceAll("\\bPhysics Dept\\.", "Physics Department");
cleanInst = cleanInst.replaceAll("(?i)\\b(?:the )?dept\\b\\.?", "The Department");

您可以鏈接所有這些替換操作(但我不知道適當的Java語法)。

關於單詞邊界\\b通常只在字母數字字符之前或之后才有意義。

例如, \\b/n\\b只會匹配/n如果它直接前面有一個字母數字字符,后跟一個非字母數字字符,那么它匹配"a/n!" 但不是"foo /n bar"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM