簡體   English   中英

Scala中的慣用正則表達式匹配

[英]Idiomatic regex matching in Scala

我試圖讓我的Scala代碼更加慣用。 現在它看起來像Java代碼。

我正在嘗試在Scala中做一個簡單的布爾正則表達式匹配函數,因為我似乎無法在標准庫中找到它(?)

我不認為try-catch和所有的結果都特別好。 另外,前提條件是'patt'只有一個組,我實際上並沒有用它。 有什么輸入?

def doesMatchRegEx(subj:String, patt:scala.util.matching.Regex) = {
    try{
        val Match = patt
        val Match(x) = subj
        true
    } catch {
        // we didnt match and therefore got an error
    case e:MatchError => false
    }
}

采用:

scala> doesMatchRegEx("foo",".*(foo).*".r)
res36: Boolean = true

scala> doesMatchRegEx("bar",".*(foo).*".r)
res37: Boolean = false
def doesMatchRegEx(subj:String, patt:scala.util.matching.Regex) = subj match {
  case patt(_) => true
  case _ => false
}

正如您所看到的,這實際上使'doMatchRegEx方法變得多余。

就像這樣:

"foo".matches(".*(foo).*") // => true
"bar".matches(".*(foo).*") // => false
".*(foo).*".r.findFirstIn("foo").isDefined // => true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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