Felix
Felix

Reputation: 1263

a regular expression

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

Answers (1)

aioobe
aioobe

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
  • The first \u is changed to \\u but while \\u is preserved as it is.

Upvotes: 3

Related Questions