Several usages of regular expressions in Scala

Several usages of
regular expressions in Scala Regular expressions are an operation aimed at strings. The main functions are matching, cutting, replacing and extracting. Regular expressions in Scala are also frequently used methods (regex.r means Is a regular expression)

1. Matching
Scala supports a variety of regular expression parsing, mainly including the following three:

  1. String.matches() method
  2. Regular expression pattern matching
  3. scala.util.matching.Regex API

//String.matches


  val s = "!123"
   println(s.matches("![a-zA-z0-9]{3}"))//true
    println(s.matches("![a-zA-z0-9]{8}"))//false

//Regular expression pattern matching


val b = """([a-z0-9]+)"""".r
"helloworld123" match {
    case b => println("匹配成功")
    case _ => println("匹配失败")
}
//匹配成功

//scala.util.matching.Regex API

There are three types of matches:

  1. findFirstMatchIn() returns the first match (Option[match])
  2. findAllMatchIn() returns all matches (regex.match)
  3. findAllIn() returns all matching results (String)
val reg ="[a-zA-Z0-9]+:[a-zA-Z0-9]+".r
val str = "name:zs,age:17"

//第一种:findFirstMatchIn()返回第一个匹配(Option[match])
 reg.findFirstMatchIn(str) match {
      case Some(x) => println(x)
      case None => println("no")
    }//name:zs
    
//第二种findAllMatchIn()返回所有匹配(regex.match)
println(reg.findAllMatchIn(str).toList)//List(name:zs, age:17)
    
//第三种findAllIn()返回所有匹配结果(String)
println(reg.findAllIn(str).mkString(","))//name:zs,age:17

2. Extract the group

val reg ="([a-zA-Z0-9]+):([a-zA-Z0-9]+)".r
val str = "name:zs,age:17"	
reg.findAllMatchIn(str).foreach(x=>println(x.group(1)))
//    name
//    age


//实用性 例如某一日志文件内容如:INFO 2000-01-07 requestURI:/c?app=0&p=1 路径为path 对其进行解析import scala.io.Source
val source = Source.fromFile("path","UTF-8")
val lines = source.getLines.toArray
val reg = """([A-Z]+) ([0-9]{4}-[0-9]{2}-[0-9]{1,2}) requestURI:(.*)""".r
//方法1
lines.map(line => reg.findAllMatchIn(line).toList.map(x => (x.group(1),x.group(2),x.group(3)))).foreach(println)
//List((INFO,2020-01-07,/c?app=0&p=1))
//方法2
lines.map(line => line match{case reg(le,ld,ad) => (le,ld,ad)})
// Array[(String)] = Array((INFO,2000-01-07,/c?app=0&p=1))
//必须逐一匹配上,不然会报错

3. Replace

//replaceFirstIn
val a = """([0-9]+)""".r
a.replaceFirstIn("123,hello! world","run")
// run,hello! world

//replaceAllIn
val a = """([0-9]+)""".r
a.replaceAllIn("123 hello world!","come on!")
//come on! hello world

4. Find


val date = """([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})""".r
"2020-5-18" match {case date(year, _*) => println((year))}
//2020
"2020-5-18" match {case date(_,mon,_*) => println(mon)}
//5

Guess you like

Origin blog.csdn.net/weixin_44695793/article/details/108675749