MOCKSTACKS
EN
Questions And Answers

More Tutorials









Scala Regular Expressions

Examples

Declaring regular expressions


The r method implicitly provided via scala.collection.immutable.StringOps produces an instance of scala.util.matching.Regex from the subject string. Scala's triple-quoted string syntax is useful here, as you do not have to escape backslashes as you would in Java:

val r0: Regex = """(\d{4})-(\d${2})-(\d{2})""".r // :)
val r1: Regex = "(\\d{4})-(\\d{2})-(\\d{2})".r // :(

scala.util.matching.Regex implements an idiomatic regular expression API for Scala as a wrapper over java.util.regex.Pattern, and the supported syntax is the same. That being said, Scala's support for multi-line string literals makes the x flag substantially more useful, enabling comments and ignoring pattern whitespace:

val dateRegex = """(?x:
 (\d{4}) # year
 -(\d{2}) # month
 -(\d{2}) # day
)""".r

There is an overloaded version of r, def r(names: String*): Regex which allows you to assign group names to your pattern captures. This is somewhat brittle as the names are disassociated from the captures, and should only be used if the regular expression will be used in multiple locations:

"""(\d{4})-(\d{2})-(\d{2})""".r("y", "m", "d").findFirstMatchIn(str) match {
 case Some(matched) =>
 val y = matched.group("y").toInt
val m = matched.group("m").toInt
 val d = matched.group("d").toInt
 java.time.LocalDate.of(y, m, d)
 case None => ???
}

Repeating matching of a pattern in a string


val re = """\((.*?)\)""".r
val str =
"(The)(example)(of)(repeating)(pattern)(in)(a)(single)(string)(I)(had)(some)(trouble)(with)(once)"
re.findAllMatchIn(str).map(_.group(1)).toList
res2: List[String] = List(The, example, of, repeating, pattern, in, a, single, string, I, had,
some, trouble, with, once)



Conclusion

In this page (written and validated by ) you learned about Scala Regular Expressions . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala js.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.