2

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}]+)(?=})

2
  • Your code has the regex as \${([^\s}]+)(?=}) but the error shows /${([^/s}]+)(?=}) - both the slashes are different, shows forward / in the error. Commented Jun 26, 2016 at 3:42
  • it was a typo, I fixed the exception Commented Jun 26, 2016 at 3:47

1 Answer 1

5

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

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

Comments

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.