I want to insert a backslash in front of each pipe:
// What i want
MyList.replaceAll(item -> item.replaceAll("|" , "\|"));
// what i´ve tried that does not work
MyList.replaceAll(item -> item.replaceAll("\\|" , "\\|"));
when executing the code I get "illegal escape character in string literal".
appreciate your help Thx :D
So you want literal backslashes in the strings? That's a nice puzzler:
String item = "This | is | a | sample".replaceAll("\\|" , "\\\\|");
System.out.println(item);
prints:
This \| is \| a \| sample
Why is this?
You have to escape literal backslashes with another backslash in Java string literals. The same applies to special RegEx symbols. So in the above example, you want to match every literal |
, so we put a \
before it (RegEx escape) and another \
(Java string escape for the first \
).