💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
**1. 正则实现方式** 我们可以使用 scala.util.matching.Regex ,或 String 自带的一些方法来完成正则工作。 <br/> **2. String实现正则** ```scala // matches:匹配返回true,否则返回false "!123".matches("[a-zA-Z0-9]{4}") // false "34Az".matches("[a-zA-Z0-9]{4}") // true // String.r:将一个字符串转换为 Regex 对象 val zPattern:Regex = "([a-zA-Z][0-9][a-zA-Z] [0-9][a-zA-Z][0-9])".r "L3R 6M2" match { // zc为第1个分组的结果,可以匹配多个分组 case zPattern(zc) => println(s"Valid zip-code:$zc") // Valid zip-code:L3R 6M2 case zc => println(s"Invalid zip-code:$zc") } ``` <br/> **3. `scala.util.matching.Regex` 实现正则** (1)返回匹配结果 ```scala def findFirstMatchIn(source: CharSequence): Option[Match] 返回第一个匹配。 def findAllMatchIn(source: CharSequence): Iterator[Match] 返回所有匹配结果。 def findAllIn(source: CharSequence) = new Regex.MatchIterator(source, this, groupNames) 返回所有匹配结果。 ``` ```scala import scala.util.matching.Regex object App{ def main(args: Array[String]): Unit = { val numPattern:Regex = "[0-9]".r var result = numPattern.findFirstMatchIn("awe43some9password") println(result) // Some(4) val stuPattern:Regex = "([0-9a-zA-Z-#() ]+):([0-9a-zA-Z-#() ]+)".r val input = "name:Jason,age:19,weight:100" for (patternMatch <- stuPattern.findAllMatchIn(input)) { // 捕获分组 println(s"key: ${patternMatch.group(1)}, value:${patternMatch.group(2)}") /* key: name, value:Jason key: age, value:19 key: weight, value:100 */ } val numPattern = "[0-9]+".r var matchValue = numPattern.findAllIn("123 Main Street Suite 2012") while(matchValue.hasNext) { println(matchValue.next()) // 123 // 2012 } } } ``` (2)字符串替换 ```scala object App{ def main(args: Array[String]): Unit = { val numPattern = "[0-9]".r var matchValueFirst = numPattern.replaceFirstIn("234 main", "abc") println(matchValueFirst) // abc34 main var matchValueAll = numPattern.replaceAllIn("234 main 456", "abc ") println(matchValueAll) // abc abc abc main abc abc abc } } ``` (3)在字符串中查找模式 ```scala object App{ def main(args: Array[String]): Unit = { val date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r "2014-05-23" match { case date(year, month, day) => println(year, month, day) // (2014,05,23) } "2014-05-23" match { case date(year, _*) => println(year) // 2014 } "2014-05-23" match { case date(_*) => println("It is date") // It is date } } } ```