0

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?

3
  • 1
    Hello, could you provide an example input and an example output? Commented Jun 15, 2022 at 10:07
  • You can't do that, because the String#replaceAll API does not support it. Commented Jun 15, 2022 at 10:09
  • Title: "how can I use backslash ... in java replaceAll()" -> you cannot! Body: "Is there any other tool can support this form?" -> different question (often closed since opinion based, point 3) Commented Jun 15, 2022 at 11:30

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.