正则表达式不匹配
Regex not matching
我希望正则表达式 "[a-zA-Z]\d{6}"
匹配 "z999999"
但它不匹配,因为映射了一个空列表:
val lines = List("z999999"); //> lines : List[String] = List(z999999)
val regex = """[a-zA-Z]\d{6}""".r //> regex : scala.util.matching.Regex = [a-zA-Z]\d{6}
val fi = lines.map(line => line match { case regex(group) => group case _ => "" })
//> fi : List[String] = List("")
我的正则表达式或我在 Scala 中使用它的方式有问题吗?
val l="z999999"
val regex = """[a-zA-Z]\d{6}""".r
regex.findAllIn(l).toList
res1: List[String] = List(z999999)
正则表达式似乎有效。
lines.map( _ match { case regex(group) => group; case _ => "" })
res2: List[String] = List("")
真奇怪。让我们看看围绕我们在 regex
.
中定义的整个表达式的捕获组会发生什么
val regex2= """([a-zA-Z]\d{6})""".r
regex2: scala.util.matching.Regex = ([a-zA-Z]\d{6})
lines.map( _ match { case regex2(group) => group; case _ => "" })
res3: List[String] = List(z999999)
万岁。
正则表达式上的 unapply 方法用于获取捕获组的结果。
正则表达式对象上还有其他方法可以匹配(例如 findAllIn、findFirstIn 等)
我希望正则表达式 "[a-zA-Z]\d{6}"
匹配 "z999999"
但它不匹配,因为映射了一个空列表:
val lines = List("z999999"); //> lines : List[String] = List(z999999)
val regex = """[a-zA-Z]\d{6}""".r //> regex : scala.util.matching.Regex = [a-zA-Z]\d{6}
val fi = lines.map(line => line match { case regex(group) => group case _ => "" })
//> fi : List[String] = List("")
我的正则表达式或我在 Scala 中使用它的方式有问题吗?
val l="z999999"
val regex = """[a-zA-Z]\d{6}""".r
regex.findAllIn(l).toList
res1: List[String] = List(z999999)
正则表达式似乎有效。
lines.map( _ match { case regex(group) => group; case _ => "" })
res2: List[String] = List("")
真奇怪。让我们看看围绕我们在 regex
.
val regex2= """([a-zA-Z]\d{6})""".r
regex2: scala.util.matching.Regex = ([a-zA-Z]\d{6})
lines.map( _ match { case regex2(group) => group; case _ => "" })
res3: List[String] = List(z999999)
万岁。
正则表达式上的 unapply 方法用于获取捕获组的结果。
正则表达式对象上还有其他方法可以匹配(例如 findAllIn、findFirstIn 等)