2017-07-17 28 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