2017-07-17 48 views
0

從來就一直在看這個例子部分matcing正則表達式使用hitEnd斯卡拉

String[] ss = { "aabb", "aa", "cc", "aac" }; 
    Pattern p = Pattern.compile("aabb"); 
    Matcher m = p.matcher(""); 

    for (String s : ss) { 
     m.reset(s); 
     if (m.matches()) { 
     System.out.printf("%-4s : match%n", s); 
     } 
     else if (m.hitEnd()) { 
     System.out.printf("%-4s : partial match%n", s); 
     } 
     else { 
     System.out.printf("%-4s : no match%n", s); 
     } 
    } 

而且我想用,hitEnd我的Scala模式匹配的正則表達式

val VERSION = "([0-2].0)" 
    val MESSAGE = s"A message with version $VERSION".r 

    def checkMessage(action: String): Boolean = { 
    action match { 
     case MESSAGE(version) => true 
     case _ => false 
    } 
    } 

我想要什麼如果某人輸入A message with version 3.0告訴他該郵件有部分匹配,但他輸入的版本不正確。

任何想法如何在scala中使用hitEnd

問候

回答

1

它有可能獲得從Scala的編譯正則表達式一個Matcher但我不認爲它會做你想要什麼。字符串"version"與模式version [0-2].0部分匹配,但字符串"version 3.0"不是。

val m = "version ([0-2].0)".r.pattern.matcher("") 

for (s <- Seq("version 1.0", "v", "version ", "version 3.0")) { 
    m.reset(s) 
    if (m.matches)  println(f"$s%-11s : match") 
    else if (m.hitEnd) println(f"$s%-11s : partial match") 
    else    println(f"$s%-11s : no match") 
} 

輸出:

version 1.0 : match 
v   : partial match 
version  : partial match 
version 3.0 : no match 

一種不同的方法是編譯兩種模式,一種爲一般的情況下,一個用於特定目標。

val prefix = "A message with version " 
val goodVer = (prefix + "([0-2].0)").r 
val someVer = (prefix + "(.*)").r 

def getVer(str: String): String = str match { 
    case goodVer(v) => s"good: $v" 
    case someVer(v) => s"wrong: $v" 
    case _   => "bad string" 
} 

getVer("A message with version 2.0") //res0: String = good: 2.0 
getVer("A message with version 3.0") //res1: String = wrong: 3.0 
getVer("A message with version:2.0") //res2: String = bad string