for example:
String s = "1/14/2017".replaceAll("^(\\d{1,2})/(\\d{1,2})/", "$2/$1/");
this Java code will switch the place of '1' and '14'.
but The form that i want is below, unfortunately Java not supported this form
String s = "1/14/2017".replaceAll("^(\\d{1,2})/(\\d{1,2})/", "\2/\1/");
Is there any other tool can support this form?
CodePudding user response:
You can't do that. And although it is not processed as back references
by the regex engine it is first a feature of the encoding of characters in a string.
If the engine supported it, you would need to encode it as \\\\2/\\\\1/
(or the real ugly \\\62\\\61
) because \
is the String escape character and what follows is taken to be raw input. So System.out.println("\101")
would print the letter A
.
But then the engine doesn't support the aforementioned alternative encoding because then the replacement pattern is taken to be just a String of "\2/\1/"
which isn't what you want.
I would imagine the $
was chosen as it has no special meaning outside of a regular expression and is an easier way to encode a back reference indicator than escaping backslashes. But I have no evidence to support that reasoning.