Skip to content

Commit 7396cca

Browse files
authored
Merge pull request #2462 from byyue/dev-2452
Elaborate Regular Expression Patterns
2 parents 99757bc + c294421 commit 7396cca

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

_tour/regular-expression-patterns.md

+32
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,35 @@ key: margin value: 0
5858
key: height value: 108px
5959
key: width value: 100
6060
```
61+
62+
Moreover, regular expressions can be used as patterns (in `match` expressions) to conveniently extract the matched groups:
63+
64+
```scala mdoc
65+
def saveContactInfomation(contact: String): Unit = {
66+
import scala.util.matching.Regex
67+
68+
val emailPattern: Regex = """^(\w+)@(\w+(.\w+)+)$""".r
69+
val phonePattern: Regex = """^(\d{3}-\d{3}-\d{4})$""".r
70+
71+
contact match {
72+
case emailPattern(localPart, domainName, _) =>
73+
println(s"Hi $localPart, we have saved your email address.")
74+
case phonePattern(phoneNumber) =>
75+
println(s"Hi, we have saved your phone number $phoneNumber.")
76+
case _ =>
77+
println("Invalid contact information, neither an email address nor phone number.")
78+
}
79+
}
80+
81+
saveContactInfomation("123-456-7890")
82+
saveContactInfomation("[email protected]")
83+
saveContactInfomation("2 Franklin St, Mars, Milky Way")
84+
```
85+
86+
The output would be:
87+
88+
```
89+
Hi, we have saved your phone number 123-456-7890.
90+
Hi JohnSmith, we have saved your email address.
91+
Invalid contact information, neither an email address nor phone number.
92+
```

0 commit comments

Comments
 (0)