如果没有匹配,替换会怎么做?(引擎盖下)

Col*_*der 11 java regex string performance replace

我有很长的字符串,如果出现,需要删除一个模式.但它出现在字符串中是一个非常罕见的边缘情况.

如果我这样做:

str = str.replace("pattern", "");
Run Code Online (Sandbox Code Playgroud)

然后看起来我正在创建一个新字符串(因为Java字符串是不可变的),如果原始字符串很好,这将是一种浪费.我应该首先检查匹配,然后只有在找到匹配时才更换?

nha*_*tdh 14

简短的回答

检查各种实现的文档,String.replace(CharSequence, CharSequence)如果没有找到匹配,似乎没有人要求该方法返回相同的字符串.

如果没有文档的要求,在没有找到匹配的情况下,实现可能会也可能不会优化方法.最好将代码编写为没有优化,以确保它在任何实现或版本的JRE上正确运行.

特别是,当找不到匹配项时,Oracle的实现(版本8-b123)返回相同的String对象,而GNU Classpath(版本0.95)返回一个新的String对象.

如果您在任何文档中找不到任何要求在未找到匹配项时String.replace(CharSequence, CharSequence)返回相同String对象的子句,请发表评论.

答案很长

下面的长答案是表明不同的实现可能会或可能不会优化未找到匹配的情况.

让我们看看Oracle的实现和GNU Classpath的String.replace(CharSequence, CharSequence)方法实现.

GNU类路径

注意:截至撰写本文时,这是正确的.虽然链接将来不太可能发生变化,但链接的内容可能会更改为较新版本的GNU Classpath,并且可能与下面引用的内容不同步.如果更改影响正确性,请发表评论.

让我们看看GNU Classpath的实现String.replace(CharSequence, CharSequence)(引用版本0.95).

public String replace (CharSequence target, CharSequence replacement)
{
    String targetString = target.toString();
    String replaceString = replacement.toString();
    int targetLength = target.length();
    int replaceLength = replacement.length();

    int startPos = this.indexOf(targetString);
    StringBuilder result = new StringBuilder(this);    
    while (startPos != -1)
    {
        // Replace the target with the replacement
        result.replace(startPos, startPos + targetLength, replaceString);

        // Search for a new occurrence of the target
        startPos = result.indexOf(targetString, startPos + replaceLength);
    }
    return result.toString();
}
Run Code Online (Sandbox Code Playgroud)

让我们检查一下源代码StringBuilder.toString().由于这决定了返回值,如果StringBuilder.toString()复制缓冲区,那么我们不需要进一步检查上面的任何代码.

/**
 * Convert this <code>StringBuilder</code> to a <code>String</code>. The
 * String is composed of the characters currently in this StringBuilder. Note
 * that the result is a copy, and that future modifications to this buffer
 * do not affect the String.
 *
 * @return the characters in this StringBuilder
 */

public String toString()
{
    return new String(this);
}
Run Code Online (Sandbox Code Playgroud)

如果文档无法说服您,请按照String构造函数进行操作.最终,String(char[], int, int, boolean)调用非公共构造函数,boolean dont_copy设置为to false,这意味着new String必须复制缓冲区.

 589:   public String(StringBuilder buffer)
 590:   {
 591:       this(buffer.value, 0, buffer.count);
 592:   }

 245:   public String(char[] data, int offset, int count)
 246:   {
 247:       this(data, offset, count, false);
 248:   }

 594:   /**
 595:    * Special constructor which can share an array when safe to do so.
 596:    *
 597:    * @param data the characters to copy
 598:    * @param offset the location to start from
 599:    * @param count the number of characters to use
 600:    * @param dont_copy true if the array is trusted, and need not be copied
 601:    * @throws NullPointerException if chars is null
 602:    * @throws StringIndexOutOfBoundsException if bounds check fails
 603:    */
 604:   String(char[] data, int offset, int count, boolean dont_copy)
 605:   {
 606:       if (offset < 0)
 607:           throw new StringIndexOutOfBoundsException("offset: " + offset);
 608:       if (count < 0)
 609:           throw new StringIndexOutOfBoundsException("count: " + count);
 610:       // equivalent to: offset + count < 0 || offset + count > data.length
 611:       if (data.length - offset < count)
 612:           throw new StringIndexOutOfBoundsException("offset + count: "
 613:                                                   + (offset + count));
 614:       if (dont_copy)
 615:       {
 616:           value = data;
 617:           this.offset = offset;
 618:       }
 619:       else
 620:       {
 621:           value = new char[count];
 622:           VMSystem.arraycopy(data, offset, value, 0, count);
 623:           this.offset = 0;
 624:       }
 625:       this.count = count;
 626:   }
Run Code Online (Sandbox Code Playgroud)

这些证据表明GNU Classpath的实现String.replace(CharSequence, CharSequence)不会返回相同的字符串.

神谕

在Oracle的实现String.replace(CharSequence, CharSequence)(引用版本8-b123)中,该方法使用Pattern类来进行替换.

public String replace(CharSequence target, CharSequence replacement) {
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
            this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
Run Code Online (Sandbox Code Playgroud)

Matcher.replaceAll(String)调用toString()函数on CharSequence并在找不到匹配项时返回它:

public String replaceAll(String replacement) {
    reset();
    boolean result = find();
    if (result) {
        StringBuffer sb = new StringBuffer();
        do {
            appendReplacement(sb, replacement);
            result = find();
        } while (result);
        appendTail(sb);
        return sb.toString();
    }
    return text.toString();
}
Run Code Online (Sandbox Code Playgroud)

String实现CharSequence接口,并且由于String将自己传递给了接口Matcher,让我们看一下String.toString:

public String toString() {
    return this;
}
Run Code Online (Sandbox Code Playgroud)

由此,我们可以得出结论,当找不到匹配项时,Oracle的实现返回相同的String.