@@ -10,6 +10,10 @@ previous-page: singleton-objects
1010
1111Регулярные выражения (Regular expression) - это специальный шаблон для поиска данных, задаваемый в виде текстовой строки. Любая строка может быть преобразована в регулярное выражение методом ` .r ` .
1212
13+ {% tabs regex-patterns_numberPattern class=tabs-scala-version %}
14+
15+ {% tab 'Scala 2' for=regex-patterns_numberPattern %}
16+
1317``` scala mdoc
1418import scala .util .matching .Regex
1519
@@ -21,14 +25,36 @@ numberPattern.findFirstMatchIn("awesomepassword") match {
2125}
2226```
2327
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+
2446В приведенном выше примере ` numberPattern ` - это ` Regex ` (регулярное выражение), которое мы используем, чтобы убедиться, что пароль содержит число.
2547
2648Используя круглые скобки можно объединять сразу несколько групп регулярных выражений.
2749
50+ {% tabs regex-patterns_keyValPattern class=tabs-scala-version %}
51+
52+ {% tab 'Scala 2' for=regex-patterns_keyValPattern %}
53+
2854``` scala mdoc
2955import scala .util .matching .Regex
3056
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
3258
3359val input : String =
3460 """ background-color: #A03300;
@@ -43,7 +69,36 @@ val input: String =
4369for (patternMatch <- keyValPattern.findAllMatchIn(input))
4470 println(s " key: ${patternMatch.group(1 )} value: ${patternMatch.group(2 )}" )
4571```
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+
46100Здесь мы обработали сразу и ключи и значения строки. В каждом совпадении есть подгруппа совпадений. Вот как выглядит результат:
101+
47102```
48103key: background-color value: #A03300
49104key: background-image value: url(img
@@ -54,3 +109,68 @@ key: margin value: 0
54109key: height value: 108px
55110key: width value: 100
56111```
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(" JohnSmith@sample.domain.com" )
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(" JohnSmith@sample.domain.com" )
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