快学Scala 第十六课 (shell调用,正则表达式,正则表达式组,stripMargin妙用)

时间:2022-12-03 15:58:41

shell调用:(管道符前加#号,执行shell用!)

     import sys.process._

     "ls -al" #| "grep x" !

正则表达式:(r表示正则表达式)

      val numPattern = """[0-9]+""".r
for (matchString <- numPattern.findAllIn("99 bottles, 98 bottles")){
println(matchString)
}

运行结果:

99
98

正则表达式组:

      val numPatternGroup = """([0-9]+)([a-z]+)""".r
for (numPatternGroup(num, item) <- numPatternGroup.findAllIn("99bottles, 98bottles")){
println(num)
// println(item)
}

运行结果:

99
98

stripMargin妙用:(分行输入,看似没有对齐,最后运行结果都是对齐的,是不是很神奇,以后再也不怕对不齐了。)

      val s = """I am Sky.
|I like to watch film.
|I like to watch TV."""
println(s.trim().stripMargin('|'))

运行结果:

I am Sky.
I like to watch film.
I like to watch TV.