0

I'd like to extract the expressions ${*} from a String.

val example = "Hello ${foo.bar} World"

But the dollar sign and the curly brackets are part of the expression syntax, so I tried to escape it.

val expr = "\\$\\{[a-zA-Z0-9\\w]*\\}".r

But this won't work and println prints nothing:

for (ex <- expr.findAllMatchIn(example)) println(ex)

Anyone has an idea what's wrong? There exists a more elegant regex?

2 Answers 2

2

That is because you are not accounting for the . in foo.bar, do this instead:

\\$\\{[a-zA-Z0-9.\\w]*\\}             // allows for a . to also be in the string

For maximum flexibility, you can do:

\\$\\{[^}]*.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, """\$\{[^}]*.""".r works very well, it is also possible to extract multiple expressions. val example2 = "hello ${foo.bar} world ${bar.foo}". Therefore I accept this answer. :)
Definitely got to rock the triple quotes, though. It makes it easier to spot mistakes.
You should definitly put more emphasis on the shortcommings of the first solution. It will only work if there are no repetitions of "}" . The second one would be the only safe way to go.
2

You can use a simpler regex, and you can make it easier to read (avoiding the need for double escaping \\) by using triple-quotes:

val example = "Hello ${foo.bar} World ${bar.foo}"
                                              //> example  : String = Hello ${foo.bar} World ${bar.foo}

val expr = """\$\{.*?\}""".r                    //> expr  : scala.util.matching.Regex = \$\{.*?\}

for (ex <- expr.findAllMatchIn(example)) println(ex)
                                              //> ${foo.bar}
                                              //| ${bar.foo}

2 Comments

Thank you! """\$\{.*\}""".r works very well, but if multiple expressions occour, it matches to much. For example val example2 = "hello ${foo.bar} world ${bar.foo}".
Fixed - I have added a non-greedy modifier (?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.