1

How to replace characters from a given string.

I wrote the following code, but here it iterates over the chars.

val chars = "\\`*{}[]()<>#+:~'%^&@?;,.\"!$=|"
var newString = inputString 
chars.map { c =>
  if (inputString.contains(c)){
    newString = newString.replace(c, '_')
  }
}

I'm looking at code similar to below. Unfortunately, it is throwing an error. Can someone help me to figure out the error?

scala> "hello:world".replaceAll("\\`*{}[]()>#+:~'%^&@<?;,\"!$=|.", "_")
java.util.regex.PatternSyntaxException: Illegal repetition near index 2
\`*{}[]()>#+:~'%^&@<?;,"!$=|.
^

It turns out that the first argument needs to be a regular expression for the argument, and not a list of characters, but I still get an error:

scala> "hello:world".replaceAll("[`*{}[]()>#+:~'%^&@<?;,\"!$=|.]", "_")
java.util.regex.PatternSyntaxException: Unclosed character class near index 29
[`*{}[]()>#+:~'%^&@<?;,"!$=|.]
                             ^
1
  • 2
    You have to escape the regex metacharacters correctly. Commented May 11, 2017 at 17:58

2 Answers 2

3

You did not escape all of the characters in the regex that need escaping. This works:

"hello:world".replaceAll("[\\`\\*{}\\[\\]()>#\\+:\\~'%\\^&@<\\?;,\"!\\$=\\|\\.]", "_")

but I'm guessing that what you really want is:

"hello:world".replaceAll("\\W", "_")
Sign up to request clarification or add additional context in comments.

2 Comments

To avoid having to Java-escape the Regex-escape slash, you can also use triple double quotes. Besides, you forgot the slash, and the fact that some special characters need not be escaped in [] clause in regex: """[\`*{}\[]()>#+:~'%^&@<?;,"!$=|.]""".
Yeah, the answer is correct. It just suffers from "backslash paranoia".
2

If you escape the square braces with backslashes, the regular expression pattern should compile:

scala> "hello:world".replaceAll("[`*{}\\[\\]()>#+:~'%^&@<?;,\"!$=|.]", "_")
res0: String = hello_world

You could probably just use the character classes to write it more succinctly:

scala> "hello:world".replaceAll("\\p{Punct}", "_")
res1: String = hello_world

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.