Reputation: 2337
I am trying to replace an \u in a url.
C:\testing\bing\utest\university.txt
when i use url=url.replaceAll("\\u", "\\\\u");
I am getting the below error May i know how to replace the \u with \u or escaping the \u
java.util.regex.PatternSyntaxException: Illegal Unicode escape sequence near index 2
\u
Upvotes: 0
Views: 1174
Reputation: 36304
You have to use it like this : url=url.replaceAll("\\\\u", "\\\\\\\\u");
. The first argument to replaceAll()
is a regex
and the second argument is a string
.
Why? :
If you look at the code of matcher.appendReplacement()
which is called from replaceAll()
, you have :
while (cursor < replacement.length()) {
char nextChar = replacement.charAt(cursor);
if (nextChar == '\\') {
So, each \
will have to be considered which leads to 4 *2 =8 \
s in the code
Upvotes: 3
Reputation: 223
url.replaceAll("\\\\u", "\\\\\\\\u")
Will produce:
C:\testing\bing\\utest\\university.txt
Upvotes: 2
Reputation: 785631
You can actually ditch the regex and use non-regex method String#replace
for this:
String repl = "C:\\testing\\bing\\utest\\university.txt".replace("\\u", "\\\\u");
//=> C:\testing\bing\\utest\\university.txt
Upvotes: 5