Kavitha
Kavitha

Reputation: 215

Regular Expression - Scala

I am new to Regular Expression and learning now. Could someone help to understand the below Regex?

val varPattern = new scala.util.matching.Regex("""(\$\{(\S+?)\})""", "fullVar", "value")

Thanks, KaviJee

Upvotes: 1

Views: 321

Answers (2)

som-snytt
som-snytt

Reputation: 39587

scala> "${abc}" match { case varPattern(full, value) => s"$full / $value" }
res0: String = ${abc} / abc

Unless you are using group names with the standard library regex, it's more usual to see:

scala> val r = """(\$\{(\S+?)\})""".r
r: scala.util.matching.Regex = (\$\{(\S+?)\})

Edit, they also allow:

scala> val r = """(\$\{(\S+?)\})""".r("full", "val")
r: scala.util.matching.Regex = (\$\{(\S+?)\})

Greedy example:

scala> val r = """(\S+?)(a*)""".r
r: scala.util.matching.Regex = (\S+?)(a*)

scala> "xyzaa" match { case r(prefix, suffix) => s"$prefix, $suffix" }
res11: String = xyz, aa

scala> val r = """(\S+)(a*)""".r
r: scala.util.matching.Regex = (\S+)(a*)

scala> "xyzaa" match { case r(prefix, suffix) => s"$prefix, $suffix" }
res12: String = "xyzaa, "

Upvotes: 1

Youssef13
Youssef13

Reputation: 4986

(\$\{(\S+?)\})

I'll try to explain it by each symbol:

( is start of grouping

\$ matches $ symbol, the backslash is because $ is a special character with another meaning

\{ matches { symbol, the backslash is because { is a special character with another meaning

(\S+?) is a group that matches one or more of non whitespace characters

\} matches } symbol, the backslash is because } is a special character with another meaning

) is end of grouping

so the whole regex should match:

${ANYWORD}

Where ANYWORD is any characters that doesn't contain whitespaces.

Upvotes: 1

Related Questions