Reputation: 1263
Now I have a String and I want to delete \n and convert \u to \\u.
If the String contains \\u,I will not change it to \\\u.
I want to use String.replaceAll(), but I don`t know how to write the regular expression.
please help me. thanks.
example:
\u => \\u
\\u => \\u (do nothing)
Upvotes: 1
Views: 269
Reputation: 420990
Here's a solution using a negative look-behind. (Changes \u
to \\u
only if it is not preceeded by a \
.)
String in = "lorem ipsum \\u dolor \\\\u sit \n amet";
System.out.println(in);
System.out.println(in.replaceAll("\\n", "")
.replaceAll("(?<!\\\\)\\\\u", "\\\\\\\\u"));
Prints:
lorem ipsum \u dolor \\u sit
amet
lorem ipsum \\u dolor \\u sit amet
\n
removed\u
is changed to \\u
but while \\u
is preserved as it is.Upvotes: 3