1

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

2 Answers 2

1
(\$\{(\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.

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

7 Comments

I was too lazy to explain. " it matches quotation mark"? I don't understand that here.
The " 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.
@mikej, I don't know Scala, I thought it's something like VB.NET, so the """ aren't included in the regex itself ?
Correct, none of the " 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.
Thank you all for your reply. I am confused about (\S+?) and (\S+). Because (\S+) and (\S+?) gives the same result. Then, what is the meaning of ?
|
1
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, "

1 Comment

Thank you all for your reply. I am confused about (\S+?) and (\S+). Because (\S+) and (\S+?) gives the same result. Then, what is the meaning of ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.