val pattern = "\\d+".r val text = "2020-04-16" //output => 2020 println(pattern.findPrefixOf(text).get)
replaceFirstIn vs replaceAllIn vs replaceSomeIn
这几个函数的作用是替换,类似python的re.sub
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
val pattern = "\\d+".r val text = "2020-01-01" // output => xxx-01-01 println(pattern.replaceFirstIn(text, "xxx").get) // output => xxx-xxx-xxx println(pattern.replaceAllIn(text, "xxx").get) // 根据匹配到的对象自定义函数去进行不同的替换 // output => year-xxx-xxx val replace_f = (m: Match) => { var r = Option("") m.group(1) match { case "2020" => r = Some("year") case _ => r = Some("xxx") } r } println(pattern.replaceSomeIn(text, replace_f))
关于scala.util.matching.Regex.Match
细节参见文档。简单用法如下:
1 2 3 4 5 6 7 8 9 10 11 12
val pattern = "(\\d+)".r("year") val text = "2020-01-01" val _match = pattern.findFirstMatchIn(text).get // 匹配到的文本 output => 2020 println(_match.source) // 匹配的起始位置 output => 0 println(_match.start) // 匹配的分组 output => 2020 println(_match.group(0)) // 匹配的分组 output => 2020 println(_match.group("year"))
一些不太习惯的地方
#1
我以为会是: 2020
1 2 3 4 5
val text = "Hello, I am Scala Regex. date:2020-01-01" val pattern = "date:(\\d+)".r