简体   繁体   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);

I'm trying to replace the "," between \\"s so I can use String.split() latter. 我试图取代","\\"s这样我就可以使用String.split()后者。

But the above just not working , the result is: 但以上只是不起作用,结果是:

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

but when I change the src string to 但是当我将src字符串更改为

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

It works well 它运作良好

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

What's the matter with the string??? 字符串有什么问题???

( and ) are regex metacharacter; ()是正则表达式元字符; they need to be escaped if you want to match it literally. 如果你想要按字面意思匹配它们,它们需要被转义。

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

The reason why you need two slashes is that because \\ in a string literal is itself an escape character, so "\\\\" is a string of length 1 containing a slash. 你需要两个斜杠的原因是因为字符串文字中的\\本身就是一个转义字符,所以"\\\\"是一个长度为1的字符串,包含一个斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM