ps0604
ps0604

Reputation: 1071

Extract variables from string with Regex

I'm trying to extract from a string variables with the following format: ${var}

Given this string:

val s = "This is a string with ${var1} and ${var2} and {var3}"

The result should be

List("var1","var2")

This is the attempt, it ends in an exception. What's wrong with this regex?

val pattern = """\${([^\s}]+)(?=})""".r
val s = "This is a string with ${var1} and ${var2} and {var3}"
val vals = pattern.findAllIn(s)

println(vals.toList)

and the exception:

Exception in thread "main" java.util.regex.PatternSyntaxException:

Illegal repetition near index 1 \${([^\s}]+)(?=})

Upvotes: 2

Views: 225

Answers (1)

rock321987
rock321987

Reputation: 11032

NOTE :- { in regex have special meaning. It denotes range. e.g. a{2,10} denotes match a in between 2 to 10 times. So you need to escape {.

Solution 1

val pattern = """\$\{([^\s}]+)(?=})""".r

You need to access the first capturing group for finding the result and then change it to list.

Solution 2

You can also use lookbehind like

val pattern = """(?<=\$\{)[^\s}]+(?=})""".r

Ideone Demo

Upvotes: 5

Related Questions