Why is String.replaceAll () not working on this line?

    //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 am trying to replace in ","between \"s, so I can use the String.split()latter.

But the above does not work, the result:

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 src string to

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

Works well

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

What happened to the string ???

+3
source share
1 answer

(and )- metacharacter of regular expressions; they must be escaped if you want to combine it literally.

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

The reason you need two slashes is because \it is itself an escape character in a string literal, therefore it "\\"is a string of length 1 containing a slash.

+5

Source: https://habr.com/ru/post/1743286/


All Articles