From 4c61807293bfe8053ea66cd538ea43b8e8adf4d4 Mon Sep 17 00:00:00 2001 From: Brian Yue Date: Wed, 6 Jul 2022 22:10:17 +0800 Subject: [PATCH 1/2] Elaborate Regular Expression Patterns --- _tour/regular-expression-patterns.md | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/_tour/regular-expression-patterns.md b/_tour/regular-expression-patterns.md index aa51821463..8f3d7fd003 100644 --- a/_tour/regular-expression-patterns.md +++ b/_tour/regular-expression-patterns.md @@ -58,3 +58,35 @@ key: margin value: 0 key: height value: 108px key: width value: 100 ``` + +Moreover, you can combine Pattern Matching and Regular Expression Patterns: + +```scala mdoc +def saveContactInfomation(contact: String): Unit = { + import scala.util.matching.Regex + + val emailPattern: Regex = """^(\w+)@(\w+(.\w+)+)$""".r + val phonePattern: Regex = """^(\d{3}-\d{3}-\d{4})$""".r + + contact match { + case emailPattern(localPart, domainName, _) => + println(s"Hi $localPart, we have saved your email address.") + case phonePattern(phoneNumber) => + println(s"Hi, we have saved your phone number $phoneNumber.") + case _ => + println("Invalid contact information, neither an email address nor phone number.") + } +} + +saveContactInfomation("123-456-7890") +saveContactInfomation("JohnSmith@sample.domain.com") +saveContactInfomation("2 Franklin St, Mars, Milky Way") +``` + +The output would be: + +``` +Hi, we have saved your phone number 123-456-7890. +Hi JohnSmith, we have saved your email address. +Invalid contact information, neither an email address nor phone number. +``` \ No newline at end of file From c2944219cee5bd05f5e3a89d591f2b8ffea5846b Mon Sep 17 00:00:00 2001 From: Brian Yue <46839413+byyue@users.noreply.github.com> Date: Wed, 6 Jul 2022 22:56:34 +0800 Subject: [PATCH 2/2] Make the description clearer Co-authored-by: Julien Richard-Foy --- _tour/regular-expression-patterns.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_tour/regular-expression-patterns.md b/_tour/regular-expression-patterns.md index 8f3d7fd003..2669df635b 100644 --- a/_tour/regular-expression-patterns.md +++ b/_tour/regular-expression-patterns.md @@ -59,7 +59,7 @@ key: height value: 108px key: width value: 100 ``` -Moreover, you can combine Pattern Matching and Regular Expression Patterns: +Moreover, regular expressions can be used as patterns (in `match` expressions) to conveniently extract the matched groups: ```scala mdoc def saveContactInfomation(contact: String): Unit = {