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 +
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
Using %s
should work.
var x = "foo"
val regex = """^%s.*$""".format(x).r
In the off case you need %s
to be a regex match term, just do
val regex = """^%s.*%s$""".format(x, "%s").r
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With