Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions _tour/regular-expression-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,35 @@ key: margin value: 0
key: height value: 108px
key: width value: 100
```

Moreover, regular expressions can be used as patterns (in `match` expressions) to conveniently extract the matched groups:

```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.
```