簡體   English   中英

為什么String.replaceAll()不能在這個String上工作?

[英]Why String.replaceAll() don't work on this String?

    //This source is a line read from a file 
    String src = "23570006,music,**,wu(),1,exam,\"Monday9,10(H2-301)\",1-10,score,";

    //This sohuld be from a matcher.group() when Pattern.compile("\".*?\"")
    String group = "\"Monday9,10(H2-301)\"";

    src = src.replaceAll("\"", "");
    group = group.replaceAll("\"", "");

    String replacement = group.replaceAll(",", "#@");
    System.out.println(src.contains(group));
    src = src.replaceAll(group, replacement);
    System.out.println(group);
    System.out.println(replacement);
    System.out.println(src);

我試圖取代","\\"s這樣我就可以使用String.split()后者。

但以上只是不起作用,結果是:

true  
Monday9,10(H2-301)  
Monday9#@10(H2-301)  
23570006,music,**,wu(),1,exam,Monday9,10(H2-301),1-10,score,

但是當我將src字符串更改為

 String src = "123\"9,10\"123";  
 String group = "\"9,10\"";

它運作良好

true  
9,10  
9#@10  
1239#@10123

字符串有什么問題???

()是正則表達式元字符; 如果你想要按字面意思匹配它們,它們需要被轉義。

String group = "\"Monday9,10\\(H2-301\\)\"";
                            ^        ^

你需要兩個斜杠的原因是因為字符串文字中的\\本身就是一個轉義字符,所以"\\\\"是一個長度為1的字符串,包含一個斜杠。

暫無
暫無

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

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