Is there a way for embedding the value of one regular expression in another one in Scala?

Viewed 65

I have some regex values that I need to use as variables for a new regex.

I want to write something like:

val lowers: Regex = "[a-z]”.r

val uppers: Regex = "[A-Z]”.r

val letters: Regex = “(lowers | uppers)*”.r

But I don’t know the right syntax for it.

If it’s possible, how can it be done in Scala?

Edit

As suggested in the comments, this question is also related to this one when the regex variable is to be added outside the regex, which does not seem to be solving the problem here.

1 Answers

You can use string interpolation to construct a regex from two other strings:

val lowers: Regex = "[a-z]".r
val uppers: Regex = "[A-Z]".r
val letters: Regex = s"($lowers|$uppers)*".r

Please mind the s prefix before the initial " of the string literal. Output:

([a-z]|[A-Z])*

Note you should be careful with spaces in the pattern, whitespace is meaningful by default.

If you want to use spaces just for formatting, for ease of reading the regex, you can use the (?x) COMMENTS ("verbose", "freespacing") modifier:

val letters: Regex = s"(?x)($lowers | $uppers)*".r

Mind you need to escape any literal whitespace char (tab, space, newline) in the pattern if you want to use this feature. Also, you will have to escape a # char as it becomes special in this mode.

Related