Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Regex with $ and String Interpolation

Tags:

scala

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 +

like image 875
Knows Not Much Avatar asked Feb 06 '17 20:02

Knows Not Much


2 Answers

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

like image 174
puhlen Avatar answered Oct 30 '22 23:10

puhlen


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
like image 37
zenofsahil Avatar answered Oct 30 '22 22:10

zenofsahil