简体   繁体   中英

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.

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

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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