ps0604 ps0604 - 1 month ago 8x
Scala Question

Replacing string containing parenthesis

In this string:

val s = "pow(10,3) + pow(10,3) + pow(10,3)"

I need to replace




So the end result would be

1000 + 1000 + 1000

I tried with

s.replaceAll("pow(10,3)", "1000")

However this doesn't work as the first argument is a regex, and the parenthesis represent a group. The statement above actually doesn't replace anything. Any ideas?


To replace a literal string, do not use replaceAll, use replace.

See this Scala demo:

val s = "pow(10,3) + pow(10,3) + pow(10,3)";
print(s.replace("pow(10,3)", "1000"));
// => 1000 + 1000 + 1000

If you need to use replaceAll, the literal parentheses must be escaped with a doubled backslash:

s.replaceAll("pow\\(10,3\\)", "1000")

Or, use a triple-quoted string literal and use a single backslash to escape the special regex metacharacters:

s.replaceAll("""pow\(10,3\)""", "1000")

See this Scala demo and another one here.

Both replaceAll and replace will replace multiple occurrences.

Beside the replace, you may use replaceAllLiterally(literal: String, replacement: String): String

See also Is there ever a reason to use Scala's StringLike.replaceAllLiterally over Java's String.replace?