簡體   English   中英

Java Pattern.matcher(StringBuffer),為什么它的行為方式與Pattern.matcher(String)不同?

[英]Java Pattern.matcher(StringBuffer), why it does not behave the same way as Pattern.matcher(String)?

我需要在循環中“縮短”一個字符串,然后再一次將其傳遞給java.regex.Pattern進行匹配。 對於某些深入參與解析和文本處理的人來說,這可能是微不足道的情況。

我面臨必須使用的情況:

string=string.substring(shortenHowMuch); //Need to shorten it from the beginning

...底層開發人員非常了解,那就是將整個字符串復制到內存的另一個地址中。 即使有HotSpot的優化(據我所知),我仍然需要確保代碼在所有可能的Java VM上以最大可能的性能變體運行。

編輯:后來我發現,上面的語句正在復制字符串,這是錯誤的。 所以我的問題應該是“下地獄” :)無論如何,請閱讀是否喜歡:) .substring不會復制,而是共享對char[]的引用,非常有趣:)

您沒有解釋使用StringBuilder時到底發生了什么,所以我無法回答原因。 但是實際上您不需要StringBuilder,因為String.substring是經過優化的,並且不會復制內部char數組。 這是內部發生的事情

public String substring(int beginIndex, int endIndex) {
        ..... 
        return ((beginIndex == 0) && (endIndex == count)) ? this :
            new String(offset + beginIndex, endIndex - beginIndex, value);
 }

// Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
    this.value = value;
    this.offset = offset;
    this.count = count;
}

不看代碼就很難說,但是您能使您的模式更通用嗎? 像是“。*原始模式”?

暫無
暫無

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

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