简体   繁体   中英

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 +

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM