1
1
---
2
2
layout : tour
3
- title : Regular Expression Patterns
3
+ title : 正则表达式
4
4
5
5
discourse : false
6
6
@@ -13,3 +13,50 @@ language: zh-cn
13
13
next-page : extractor-objects
14
14
previous-page : singleton-objects
15
15
---
16
+
17
+ 正则表达式是一类特殊的字符串,可以用来在数据中寻找特定模式。 任何字符串都可以通过调用 ` .r ` 方法来转换成正则表达式。
18
+
19
+ ``` tut
20
+ import scala.util.matching.Regex
21
+
22
+ val numberPattern: Regex = "[0-9]".r
23
+
24
+ numberPattern.findFirstMatchIn("awesomepassword") match {
25
+ case Some(_) => println("Password OK")
26
+ case None => println("Password must contain a number")
27
+ }
28
+ ```
29
+
30
+ 在上例中,常量 ` numberPattern ` 是一个 ` Regex ` 类型的实例(正则表达式),这里用来确保密码中含有一个数字。
31
+
32
+ 你也可以用圆括号括起多个正则表达式,以便一次寻找多个值。
33
+
34
+ ``` tut
35
+ import scala.util.matching.Regex
36
+
37
+ val keyValPattern: Regex = "([0-9a-zA-Z-#() ]+): ([0-9a-zA-Z-#() ]+)".r
38
+
39
+ val input: String =
40
+ """background-color: #A03300;
41
+ |background-image: url(img/header100.png);
42
+ |background-position: top center;
43
+ |background-repeat: repeat-x;
44
+ |background-size: 2160px 108px;
45
+ |margin: 0;
46
+ |height: 108px;
47
+ |width: 100%;""".stripMargin
48
+
49
+ for (patternMatch <- keyValPattern.findAllMatchIn(input))
50
+ println(s"key: ${patternMatch.group(1)} value: ${patternMatch.group(2)}")
51
+ ```
52
+ 此例中我们从字符串中解析出多组键值对。每一个匹配值都包含一组子匹配值。结果如下:
53
+ ```
54
+ key: background-color value: #A03300
55
+ key: background-image value: url(img
56
+ key: background-position value: top center
57
+ key: background-repeat value: repeat-x
58
+ key: background-size value: 2160px 108px
59
+ key: margin value: 0
60
+ key: height value: 108px
61
+ key: width value: 100
62
+ ```
0 commit comments