Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace \u0026 with &?

Tags:

java

regex

In Java, I need to change this:

myid=460\u0026url=http%3A%2F%2Fr20-xxxx

...to this:

myid=460&url=http%3A%2F%2Fr20-xxxx

Here's what I've tried:

String map = "myid=460\\u0026url=http%3A%2F%2Fr20-xxxx";

p = Pattern.compile("\\u0026");
m = p.matcher(map);

if (m.find()) {
    String ret = m.replaceAll("&");
}

...but it cannot find the \u0026.

like image 414
Yan Gao Avatar asked Jan 27 '26 14:01

Yan Gao


1 Answers

If you must use a regex, then you must escape the backslash that is in the Java string. Then you must escape both backslashes for regex interpretation. Try

p = Pattern.compile("\\\\u0026");

But a simple replace should suffice (it doesn't use regex), with only one iteration of escape the backslash, for Java:

ret = map.replace("\\u0026", "&");
like image 188
rgettman Avatar answered Jan 30 '26 03:01

rgettman