[英]Using regex with filter in Scala
The use of below regex
does not match value : charIntIntIntIntIntInt
: 以下regex
的使用与值不匹配: charIntIntIntIntIntInt
:
val regex = "([a-zA-Z]\\d\\d\\d\\d\\d\\d)"
//> regex : String = ([a-zA-Z]\d\d\d\d\d\d)
val f = List("b111111").filter(fi => fi startsWith regex)
//> f : List[String] = List()
f
is an empty List, it should contain b111111
f
是一个空List,它应该包含b111111
When I use this regex on https://www.regex101.com/ then it correctly matches the String. 当我在https://www.regex101.com/上使用此正则表达式时,它正确匹配字符串。
Is there a problem with how I'm filtering ? 我的过滤方式有问题吗?
How about using the Scala language Regex features like: 如何使用Scala语言Regex功能如下:
val regex = """^([a-zA-Z]\d{6})""".r // enables you to drop escaping \'s
val f = List("b111111").filter { s => regex.findFirstIn(s).isDefined }
see http://www.scala-lang.org/api/current/index.html#scala.util.matching.Regex for more details 有关详细信息,请参阅http://www.scala-lang.org/api/current/index.html#scala.util.matching.Regex
Need to use matches
instead of startsWith
需要使用matches
而不是startsWith
This is detailed in String.class 这在String.class中有详细说明
This works : 这有效:
val regex = "([a-zA-Z]\\d\\d\\d\\d\\d\\d)"
val f = List("b111111").filter(fi => fi matches regex)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.