正则表达式是可以用来在数据中查找模式(或缺乏模式)的字符串。任何字符串都可以使用 .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")
}
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)}")
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) do
println(s"key: ${patternMatch.group(1)} value: ${patternMatch.group(2)}")
这里我们解析字符串的键和值。每个匹配项都有一组子匹配项。以下是输出
key: background-color value: #A03300
key: background-image value: url(img/header100.png)
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
此外,正则表达式可以用作模式(在 match
表达式中)以方便地提取匹配的组
def saveContactInformation(contact: String): Unit = {
import scala.util.matching.Regex
val emailPattern: Regex = """^(\w+)@(\w+(.\w+)+)$""".r
val phonePattern: Regex = """^(\d{3}-\d{3}-\d{4})$""".r
contact match {
case emailPattern(localPart, domainName, _) =>
println(s"Hi $localPart, we have saved your email address.")
case phonePattern(phoneNumber) =>
println(s"Hi, we have saved your phone number $phoneNumber.")
case _ =>
println("Invalid contact information, neither an email address nor phone number.")
}
}
saveContactInformation("123-456-7890")
saveContactInformation("[email protected]")
saveContactInformation("2 Franklin St, Mars, Milky Way")
def saveContactInformation(contact: String): Unit =
import scala.util.matching.Regex
val emailPattern: Regex = """^(\w+)@(\w+(.\w+)+)$""".r
val phonePattern: Regex = """^(\d{3}-\d{3}-\d{4})$""".r
contact match
case emailPattern(localPart, domainName, _) =>
println(s"Hi $localPart, we have saved your email address.")
case phonePattern(phoneNumber) =>
println(s"Hi, we have saved your phone number $phoneNumber.")
case _ =>
println("Invalid contact information, neither an email address nor phone number.")
saveContactInformation("123-456-7890")
saveContactInformation("[email protected]")
saveContactInformation("2 Franklin St, Mars, Milky Way")
输出将是
Hi, we have saved your phone number 123-456-7890.
Hi JohnSmith, we have saved your email address.
Invalid contact information, neither an email address nor phone number.