一、scala支持多种正则表达式解析方式
- String.matches()方法
- 正则表达式模式匹配
- scala.util.matching.Regex API
String.matches()方法
案例演示:
println("!123".matches("[a-zA-Z0-9]{3}")) //false
println("1123".matches("[a-zA-Z0-9]{4}")) //true
正则表达式的模式匹配
代码解析:
- 创建正则表达式匹配规则
- 创建需要匹配的字符创对象
- 使用match进行规则匹配
案例演示:
object RegexDemo01 extends App {
//模式匹配
val re: Regex = "([a-zA-Z][0-9][a-zA-Z] [0-9][a-zA-Z][0-9])".r
"L3R 6M2" match {
case re(x) => println("Valid zip-code:" + x)
case x => println("Invalid zip-code: " + x)
}
}
scala.util.matching.Regex
指定匹配规则
- findFirstMatchIn() 返回第一个匹配(Option[Match])
- findAllMatchIn() 返回所有匹配结果(Regex.Match)
- findAllIn() 返回所有匹配结果(String)
findFirstMatchIn()
val num: Regex = "[0-9]".r()
num.findFirstMatchIn("aaa") match {
case Some(_) => println("Password OK") //匹配成功
case None => println("Password must contain a number") //为匹配到
}
findAllMatchIn()
private val maybeMatch: Option[Regex.Match] = num.findFirstMatchIn("some1password")
maybeMatch.foreach(println)
findAllIn()
for (elem <- num.findAllMatchIn("123")) {
println(elem)
}
字符串替换
使用ReplaceFirstIn
将匹配到的第一个替换掉
//匹配不能遇到空格,遇到则匹配结束
println("[0-9]+".r.replaceFirstIn("23 4 hello world 789 hello", "0000"))
//0000 hello world 789 hello
使用replaceAllIn
将匹配到的所有的替换掉
println("[0-9]+".r.replaceAllIn("23 4 hello world 789 hello", "0000"))
//0000 hello world 0000 hello