建议使用 replaceAll 方法重新替换 Java 字符串中的所有文本实例

Advice re replacing all instances of text in Java string using method replaceAll

我需要替换 Java 字符串中的文本实例,我目前正在使用 replaceAll 方法,如下所示:

    String originalText = ("The City of London has existed for approximately 2000 years and the City of London remains to this day.");
    String originalKeyword = ("City of London");
    String revisedKeyword = ("");
    if (String_Utils.getLengthOfKeyword(originalKeyword) > 1) {
        revisedKeyword = String_Utils.removeChar(originalKeyword, ' ');
    }
    else {
        revisedKeyword = originalKeyword;        
    }        
    String revisedText = originalText.replaceAll(originalKeyword, revisedKeyword);        
    System.out.println("Original text: " + originalText);
    System.out.println("Revised text: " + revisedText);
    System.out.println("Original keyword: " + originalKeyword);
    System.out.println("Revised keyword: " + revisedKeyword);

上面的目的是保存一个没有空格的原始关键字的修改版本,如果关键字中的单词数超过一个,则替换字符串中所有原始关键字的实例。

鉴于这将是一个批处理操作,有人知道是否有更好的方法来批量替换 Java 字符串中的文本吗?还是有关于replaceAll的陷阱?

String originalText = ("The City of London has existed for approximately 2000 years and the City of London remains to this day.");
String originalKeyword = ("City of London");
String revisedKeyword = ("");

"to save a revised version of the original keyword without spaces"

String newVersion = new String(originalKeyword);
revisedKeyword = newVersion.replaceAll(" ","");

"and if the number of words in the keyword is more than one, then replace all instances of the original keyword in the string."

int lengthWord = originalKeyword.split(" ").length;
if(lengthWord > 0){ 
    originalText.replaceAll(originalKeyword , revisedKeyword);
}
    public static void main(String[] args) {


        String originalText = ("The City of London has existed for approximately 2000 years and the City of London remains to this day.");
        String originalKeyword = ("City of London");
        String revisedKeyword = ("");

        String[] arr = originalText.split(originalKeyword);
        String newString = "";

        for(int i = 0 ; i < arr.length ; i += 2) {

            if(i < (arr.length -1)) {
                newString += arr[i] + revisedKeyword + arr[i+1];
            }
            else {
                newString +=  revisedKeyword + arr[i];
            }
        }
        System.out.println(newString);
}

这里newString就是你要找的。

请注意,在内部,replaceAll() 使用编译模式来匹配接收到的字符串。如果你想在不同的原始文本中替换相同的关键字,你可能需要先缓存编译后的模式。如果这只是一次性的事情,replaceAll() 似乎没问题。
更快的实现将涉及从包含原始文本的字符数组实现替换方法,手动识别每个子字符串并替换它。 另一种可能的方法是使用 StringBuilder, keeping track of the internal index of the last match and using replace() 直接替换关键字。任何避免由 Pattern 和字符串的不变性引起的开销的东西。

不过,必须对这些进行基准测试以确定真正的需求。 replaceAll() 可能足以满足您提出的案例。