0

I want to escape different characters (#, $, %, &, \, ^, _, {, }, ~) in a given Java String with a backslash (# becomes \#, $ becomes \$ and so on).

Is it possible to archieve this without calling the String#replace or String#replaceAll method multiple times on the string?

5
  • Yes, it's possible. Can't you find a strategy for doing that? Using a loop for example? Commented Mar 12, 2017 at 14:49
  • Why would you want to call String#replaceAll multiple times? It uses regex so you can find each of special character and replace it with \ followed by what was found. Commented Mar 12, 2017 at 14:53
  • @Pshemo can you explain a little bit more how to do that? Commented Mar 12, 2017 at 15:01
  • Take a look at Harald's answer. He posted code representing what I meant. In short we can use $x notation in replacement part to represent match from group x. Since group 0 represents entire match we can write $0 to use what regex found. Commented Mar 12, 2017 at 15:04
  • @Pshemo thank you for your explanation. That was just what I was looking for. Thank you Commented Mar 12, 2017 at 15:15

1 Answer 1

5

You can use the following regular expression

String escaped = s.replaceAll("[" + Pattern.quote("#$%&\\^_{}~") + "]",
    Matcher.quoteReplacement("\\")+"$0")
Sign up to request clarification or add additional context in comments.

1 Comment

That was just what I was looking for. Thank you

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.