2017-04-24 80 views
3

我想提取匹配絲束正則表達式模式我定義的一個字符串的一部分:模式匹配提取字符串的Scala

//should match R0010, R0100,R0300 etc 
    val rPat="[R]{1}[0-9]{4}".r 
    // should match P.25.01.21 , P.27.03.25 etc 
    val pPat="[P]{1}[.]{1}[0-9]{2}[.]{1}[0-9]{2}[.]{1}[0-9]{2}".r 

當我現在定義我的方法來提取的元素爲:

val matcher= (s:String) => s match {case pPat(el)=> println(el) // print the P.25.01.25 
             case rPat(el)=>println(el) // print R0100 
             case _ => println("no match")} 

並測試它例如使用:

val pSt=" P.25.01.21 - Hello whats going on?" 
    matcher(pSt)//prints "no match" but should print P.25.01.21 
    val rSt= "R0010 test test 3,870" 
    matcher(rSt) //prints also "no match" but should print R0010 
    //check if regex is wrong 
    val pHead="P.25.01.21" 
    pHead.matches(pPat.toString)//returns true 
    val rHead="R0010" 
    rHead.matches(rPat.toString)//return true 

我不知道,如果正則表達式是錯誤的,但比賽方法作品在元素上。那麼這種方法有什麼問題呢?

回答

2

當您使用模式與字符串匹配,你需要牢記的是:

  • 傳遞需要將整場比賽的.r模式字符串,否則,不會返回任何匹配(解決方法是製作圖案)
  • 將其設爲非錨定後,請注意不需要的匹配:R[0-9]{4}將匹配CSR123456R1234(解決方案是根據您的實際需求是什麼,通常是字邊界不夠,或負可用於\blookarounds不同)
  • 裏面一個match塊,正則表達式匹配功能需要捕獲組是如果您想獲得一些價值(如您在pPat(el)rPat(el)中將其定義爲el)。

所以,我建議following solution

val rPat="""\b(R\d{4})\b""".r.unanchored 
val pPat="""\b(P\.\d{2}\.\d{2}\.\d{2})\b""".r.unanchored 

val matcher= (s:String) => s match {case pPat(el)=> println(el) // print the P.25.01.25 
    case rPat(el)=>println(el) // print R0100 
    case _ => println("no match") 
} 

然後,

val pSt=" P.25.01.21 - Hello whats going on?" 
matcher(pSt) // => P.25.01.21 
val pSt2_bad=" CP.2334565.01124.212 - Hello whats going on?" 
matcher(pSt2_bad) // => no match 
val rSt= "R0010 test test 3,870" 
matcher(rSt) // => R0010 
val rSt2_bad = "CSR00105 test test 3,870" 
matcher(rSt2_bad) // => no match 

的一些注意事項上的圖案:

  • \b - 領先字邊界
  • (R\d{4}) - 捕獲組匹配是4位數
  • \b - 尾隨字邊界

由於用來定義字符串文字的三重引號,沒有必要爲了躲避反斜槓。

1

介紹組在你的模式:

val rPat=".*([R]{1}[0-9]{4}).*".r 

val pPat=".*([P]{1}[.]{1}[0-9]{2}[.]{1}[0-9]{2}[.]{1}[0-9]{2}).*".r 

... 

scala> matcher(pSt) 
P.25.01.21 

scala> matcher(rSt) 
R0010 
+0

謝謝你的工作! –

0

如果以下列方式編寫代碼,則會生成所需的結果。參考API文檔,接着是http://www.scala-lang.org/api/2.12.1/scala/util/matching/Regex.html

//should match R0010, R0100,R0300 etc 
    val rPat="[R]{1}[0-9]{4}".r 
    // should match P.25.01.21 , P.27.03.25 etc 
    val pPat="[P]{1}[.]{1}[0-9]{2}[.]{1}[0-9]{2}[.]{1}[0-9]{2}".r 


    def main(args: Array[String]) { 
    val pSt=" P.25.01.21 - Hello whats going on?" 
    val pPatMatches = pPat.findAllIn(pSt); 
    pPatMatches.foreach(println) 
    val rSt= "R0010 test test 3,870" 
    val rPatMatches = rPat.findAllIn(rSt); 
    rPatMatches.foreach(println) 

    } 

請讓我知道是否適合你。