Scala正则表达式模式

xiaoxiao2021-02-28  93

正则表达式是用于找出数据中模式的字符串。任何字符串都可以使用.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
转载请注明原文地址: https://www.6miu.com/read-47233.html

最新回复(0)