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
(\$\{(\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.
" characters are not part of the regexp. Scala's triple quotes """ are used in place of a single quotes around the regexp string in order to avoid the need to escape the backslashes in \$, \{ etc." are part of the regexp. In a regular string = val pattern = "\n"` the backslash is used for control characters such as newline, tab etc. If we want a literal backslash as part of a string we'd need to escape it e.g. val pattern = "\\$"`. As an alternative to doing that a bunch of times a triple-quoted string (where backslashes are treated literally) can be used.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, "