0
replace(/[.?+^$[\]\\(){}|-]/g, '\\$&');

But it doesn't work in Java. So I changed the code as follows.

replace(/[.?+^$[\\]\\\\(){}|-]/g, '\\\\$&');

It doesn't work when I change it. Please help me :(

2
  • In java, you need to use double quotes instead of quote slashes for regex: "[.?+^$[\\]\\\\(){}|-]". Also, if you want to replace all occurrences, you need to use String.replaceAll Commented Nov 20, 2020 at 2:00
  • Thank you for your answer. replaceAll(?"[?]+^$[\]\\\\(){}|-", "\\\\$&") results in a blank space. Commented Nov 20, 2020 at 3:35

1 Answer 1

2

In Java, replace does not take a regex in the constructor, for that you need replaceFirst.

But as you are using the /g flag in Javascript for all replacements, you can use replaceAll.

In Javascript, this part $& in the replacement points to the full match.

So you want to replace the full match (which is one of these characters [.?+^$[\]\\(){}|-]) prepended by a \

In Java you can use $0 instead to refer to the full match.

You can also escape the opening square bracket in the character class \\[

For example

System.out.println("{test?test^}".replaceAll("[.?+^$\\[\\]\\\\()\\{}|-]", "\\\\$0"));

See a Java demo

Output

\{test\?test\^\}

The same output in Javascript

console.log("{test?test^}".replace(/[.?+^$[\]\\(){}|-]/g, '\\$&'));

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.