Knows Not Much Knows Not Much - 4 years ago 143
Scala Question

Scala Regex with $ and String Interpolation

I am writing a regex in scala

val regex = "^foo.*$".r

this is great but if I want to do

var x = "foo"
val regex = s"""^$x.*$""".r

now we have a problem because $ is ambiguous. is it possible to have string interpolation and be able to write a regex as well?

I can do something like

val x = "foo"
val regex = ("^" + x + ".*$").r

but I don't like to do a

Answer Source

You can use $$ to have a literal $ in an interpolated string.

You should use the raw interpolator when enclosing a string in triple-quotes as the s interpolator will re-enable escape sequences that you might expect to be interpreted literally in triple-quotes. It doesn't make a difference in your specific case but it's good to keep in mind.

so val regex = raw"""^$x.*$$""".r

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download