File tree 1 file changed +32
-0
lines changed
1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -58,3 +58,35 @@ key: margin value: 0
58
58
key: height value: 108px
59
59
key: width value: 100
60
60
```
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(" JohnSmith@sample.domain.com" )
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
+ ```
You can’t perform that action at this time.
0 commit comments