Scala/Java/Kotlin: How to replace left and right brackets in a String (replaceFirst, replaceAll)

Scala/Java/Kotlin String FAQ: How do I replace left and right brackets — the [ and ] characters — in a String when using methods like replaceFirst and replaceAll?

Solution

If you’re using Scala, Java, Kotlin, or other JVM languages, and need to replace left or right brackets in a String, I found the following solution, which seems to work well with String methods like replaceFirst and replaceAll.

Note that I’ll show these examples using Scala, but they should work with Java, and Kotlin as well.

Example

First, given a mulitline String like this:

val input = """
foo [test] foo
bar [test] bar
baz [else] baz
""".trim

You can use replaceFirst and replaceAll like this:

val first = input.replaceFirst("\\[test]", "")
val all = input.replaceAll("\\[test]", "")

After a little bit of testing, I found that the \\ characters are needed before the left bracket, but no escape characters are needed before the right bracket.

The Scala REPL (playground) shows how this works:

amm> val input = """
     foo [test] foo
     bar [test] bar
     baz [else] baz
     """.trim 
input: String = """foo [test] foo
bar [test] bar
baz [else] baz"""

amm> val first = input.replaceFirst("\\[test]", "") 
first: String = """foo  foo
bar [test] bar
baz [else] baz"""

amm> val all = input.replaceAll("\\[test]", "") 
all: String = """foo  foo
bar  bar
baz [else] baz"""

As shown in that input and output, with replaceFirst, the first instance of [test] is removed, and with replaceAll, all occurrences of [test] are removed.

So in summary, if you needed to see how to replace left or right brackets in a String, I hope these examples are helpful.