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.
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, "
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.