簡體   English   中英

在Scala中使用帶有過濾器的正則表達式

[英]Using regex with filter in Scala

以下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是一個空List,它應該包含b111111

當我在https://www.regex101.com/上使用此正則表達式時,它正確匹配字符串。

我的過濾方式有問題嗎?

如何使用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 }

有關詳細信息,請參閱http://www.scala-lang.org/api/current/index.html#scala.util.matching.Regex

需要使用matches而不是startsWith

這在String.class中有詳細說明

這有效:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM