正则表达式是用来寻找在数据中符合某个模式的字符串。任何字符串都可以使用 .r
方法转换成正则表达式。
import scala.util.matching.Regex
val numberPattern: Regex = "[0-9]".r
numberPattern.findFirstMatchIn("awesomepassword") match {
case Some(_) => println("Password OK")
case None => println("Password must contain a number")
}
在上面的例子中,numberPattern
是一个 Regex
类型的常量,我们可以用它来确认一个密码字符串是否包含一个数字。
你也可以使用括号同时匹配好几组正则表达式。
import scala.util.matching.Regex
val keyValPattern: Regex = "([0-9a-zA-Z-#() ]+): ([0-9a-zA-Z-#() ]+)".r
val input: String =
"""background-color: #A03300;
|background-image: url(img/header100.png);
|background-position: top center;
|background-repeat: repeat-x;
|background-size: 2160px 108px;
|margin: 0;
|height: 108px;
|width: 100%;""".stripMargin
for (patternMatch <- keyValPattern.findAllMatchIn(input))
println(s"key: ${patternMatch.group(1)} value: ${patternMatch.group(2)}")
我们解析出了字符串中的属性名和对应的值。每一次匹配都有一组子匹配。这里是输出的结果:
key: background-color value: #A03300
key: background-image value: url(img
key: background-position value: top center
key: background-repeat value: repeat-x
key: background-size value: 2160px 108px
key: margin value: 0
key: height value: 108px
key: width value: 100