package Demo001.scala02
object RegexDemo extends App {
//"2019-04-11"
//三个双引号为自然语言不用\转义 等同于 "(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)".r
val data1="""(\d\d\d\d)-(\d\d)-(\d\d)""".r //.r的返回值是Regex 就是正则表达式的意思
val x="2019-04-11" match {
case data1(x,y,z) => (x,y)//可以根据需求拿出年月 (2019,04)
case _ =>("Hello Regex")
}
println(x)
//===========weblog Regex
val webLog = "110.52.250.126 - - [30/May/2013:17:38:20 +0800]"
val webRegex="""(\d\d\d.\d\d.\d\d\d.\d\d\d)\D\D(\d\d/\D\D\D/\d\d\d\d:\d\d:\d\d:\d\d+\d\d\d\d)""".r
webLog match {
case webRegex => println(webRegex)
}
//=====================weblog Regex
val dates = "Important dates in history: 2004-01-20, 1958-09-05, 2010-10-06, 2011-07-15"
//findFirstIn和findFirstMatchIn是值匹配到第一个成功匹配的数据.
val firstdata=data1.findFirstIn(dates)
val firstyear=for(m <- data1 findFirstMatchIn dates) yield m group 1 //findfirstmatchin 底层用的是options集合所以返回的是some
println(firstdata)//Some(2004-01-20)
println(firstyear)//Some(2004)
for(g <- data1 findAllMatchIn(dates))println(g.subgroups)//相当于把全部符合类型的数组返回
//List(2004, 01, 20)
// List(1958, 09, 05)
// List(2010, 10, 06)
// List(2011, 07, 15
}
scala正则
最新推荐文章于 2023-08-10 16:48:39 发布