簡體   English   中英

在java中的String replaceAll方法未提供預期的結果

[英]In java String replaceAll method not giving expected result

以下是使用replaceAll方法未給出預期結果的程序。

public class HelloWorld{
     public static void main(String []args){
         String source = "Stack Overflow is a question and answer (site) for professional.";
         String txt1 = "question and answer (site) for";
        String text2 = "changed question and answer (site) for";
        source = source.replaceAll(txt1, text2);
        System.out.println(source);
     }
}

如果我在源,text1和text2中刪除單詞“ site”的括號(即括號),則將得到正確的結果。 有人可以幫我解決問題嗎?

replaceAll方法以正則表達式為依據。 由於括號是正則表達式中使用的字符,因此這些字符不能直接識別。 您可以使用Pattern.quote來獲取文字字符串。

括號用於分組。 如果您希望它們是文字,

String txt1 = "question and answer \\(site\\) for";

這僅適用於模式,不適用於替換字符串。

如果使用通配符,則在正則表達式中使用分組來訪問匹配字符串的某些部分。

"abc(\\d+)def"

這樣,您可以在匹配后確定中間部分匹配的數字。

或者你用

source = source.replace(txt1, text2);

沒有任何正則表達式向導。 (它仍然替換所有出現的事件。)

如果您只是要替換純字符串並且根本不使用正則表達式,則無需更改括號。 相反,您只需要使用搜索字符串中的Pattern.quote讓Java轉義所有特殊字符,如下所示:

public class HelloWorld{
     public static void main(String []args){
         String source = "Stack Overflow is a question and answer (site) for professional.";
         String txt1 = "question and answer (site) for";
        String text2 = "changed question and answer (site) for";
        source = source.replaceAll(Pattern.quote(txt1), text2);
        System.out.println(source);
     }
}

暫無
暫無

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

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