@@ -10,6 +10,10 @@ previous-page: singleton-objects
10
10
11
11
Регулярные выражения (Regular expression) - это специальный шаблон для поиска данных, задаваемый в виде текстовой строки. Любая строка может быть преобразована в регулярное выражение методом ` .r ` .
12
12
13
+ {% tabs regex-patterns_numberPattern class=tabs-scala-version %}
14
+
15
+ {% tab 'Scala 2' for=regex-patterns_numberPattern %}
16
+
13
17
``` scala mdoc
14
18
import scala .util .matching .Regex
15
19
@@ -21,14 +25,36 @@ numberPattern.findFirstMatchIn("awesomepassword") match {
21
25
}
22
26
```
23
27
28
+ {% endtab %}
29
+
30
+ {% tab 'Scala 3' for=regex-patterns_numberPattern %}
31
+
32
+ ``` scala
33
+ import scala .util .matching .Regex
34
+
35
+ val numberPattern : Regex = " [0-9]" .r
36
+
37
+ numberPattern.findFirstMatchIn(" awesomepassword" ) match
38
+ case Some (_) => println(" Password OK" )
39
+ case None => println(" Password must contain a number" )
40
+ ```
41
+
42
+ {% endtab %}
43
+
44
+ {% endtabs %}
45
+
24
46
В приведенном выше примере ` numberPattern ` - это ` Regex ` (регулярное выражение), которое мы используем, чтобы убедиться, что пароль содержит число.
25
47
26
48
Используя круглые скобки можно объединять сразу несколько групп регулярных выражений.
27
49
50
+ {% tabs regex-patterns_keyValPattern class=tabs-scala-version %}
51
+
52
+ {% tab 'Scala 2' for=regex-patterns_keyValPattern %}
53
+
28
54
``` scala mdoc
29
55
import scala .util .matching .Regex
30
56
31
- val keyValPattern : Regex = " ([0-9a-zA-Z-#() ]+): ([0-9a-zA-Z-#() ]+)" .r
57
+ val keyValPattern : Regex = " ([0-9a-zA-Z- ]+): ([0-9a-zA-Z-#()/. ]+)" .r
32
58
33
59
val input : String =
34
60
""" background-color: #A03300;
@@ -43,7 +69,36 @@ val input: String =
43
69
for (patternMatch <- keyValPattern.findAllMatchIn(input))
44
70
println(s " key: ${patternMatch.group(1 )} value: ${patternMatch.group(2 )}" )
45
71
```
72
+
73
+ {% endtab %}
74
+
75
+ {% tab 'Scala 3' for=regex-patterns_keyValPattern %}
76
+
77
+ ``` scala
78
+ import scala .util .matching .Regex
79
+
80
+ val keyValPattern : Regex = " ([0-9a-zA-Z- ]+): ([0-9a-zA-Z-#()/. ]+)" .r
81
+
82
+ val input : String =
83
+ """ background-color: #A03300;
84
+ |background-image: url(img/header100.png);
85
+ |background-position: top center;
86
+ |background-repeat: repeat-x;
87
+ |background-size: 2160px 108px;
88
+ |margin: 0;
89
+ |height: 108px;
90
+ |width: 100%;""" .stripMargin
91
+
92
+ for patternMatch <- keyValPattern.findAllMatchIn(input) do
93
+ println(s " key: ${patternMatch.group(1 )} value: ${patternMatch.group(2 )}" )
94
+ ```
95
+
96
+ {% endtab %}
97
+
98
+ {% endtabs %}
99
+
46
100
Здесь мы обработали сразу и ключи и значения строки. В каждом совпадении есть подгруппа совпадений. Вот как выглядит результат:
101
+
47
102
```
48
103
key: background-color value: #A03300
49
104
key: background-image value: url(img
@@ -54,3 +109,68 @@ key: margin value: 0
54
109
key: height value: 108px
55
110
key: width value: 100
56
111
```
112
+
113
+ Кроме того, регулярные выражения можно использовать в качестве шаблонов (в выражениях ` match ` )
114
+ для удобного извлечения совпавших групп:
115
+
116
+ {% tabs regex-patterns_saveContactInformation class=tabs-scala-version %}
117
+
118
+ {% tab 'Scala 2' for=regex-patterns_saveContactInformation %}
119
+
120
+ ``` scala mdoc
121
+ def saveContactInformation (contact : String ): Unit = {
122
+ import scala .util .matching .Regex
123
+
124
+ val emailPattern : Regex = """ ^(\w+)@(\w+(.\w+)+)$""" .r
125
+ val phonePattern : Regex = """ ^(\d{3}-\d{3}-\d{4})$""" .r
126
+
127
+ contact match {
128
+ case emailPattern(localPart, domainName, _) =>
129
+ println(s " Hi $localPart, we have saved your email address. " )
130
+ case phonePattern(phoneNumber) =>
131
+ println(s " Hi, we have saved your phone number $phoneNumber. " )
132
+ case _ =>
133
+ println(" Invalid contact information, neither an email address nor phone number." )
134
+ }
135
+ }
136
+
137
+ saveContactInformation(" 123-456-7890" )
138
+ saveContactInformation(
" [email protected] " )
139
+ saveContactInformation(" 2 Franklin St, Mars, Milky Way" )
140
+ ```
141
+
142
+ {% endtab %}
143
+
144
+ {% tab 'Scala 3' for=regex-patterns_saveContactInformation %}
145
+
146
+ ``` scala
147
+ def saveContactInformation (contact : String ): Unit =
148
+ import scala .util .matching .Regex
149
+
150
+ val emailPattern : Regex = """ ^(\w+)@(\w+(.\w+)+)$""" .r
151
+ val phonePattern : Regex = """ ^(\d{3}-\d{3}-\d{4})$""" .r
152
+
153
+ contact match
154
+ case emailPattern(localPart, domainName, _) =>
155
+ println(s " Hi $localPart, we have saved your email address. " )
156
+ case phonePattern(phoneNumber) =>
157
+ println(s " Hi, we have saved your phone number $phoneNumber. " )
158
+ case _ =>
159
+ println(" Invalid contact information, neither an email address nor phone number." )
160
+
161
+ saveContactInformation(" 123-456-7890" )
162
+ saveContactInformation(
" [email protected] " )
163
+ saveContactInformation(" 2 Franklin St, Mars, Milky Way" )
164
+ ```
165
+
166
+ {% endtab %}
167
+
168
+ {% endtabs %}
169
+
170
+ Вот как выглядит результат:
171
+
172
+ ```
173
+ Hi, we have saved your phone number 123-456-7890.
174
+ Hi JohnSmith, we have saved your email address.
175
+ Invalid contact information, neither an email address nor phone number.
176
+ ```
0 commit comments