2013-11-01 68 views
0

可有人爲什麼下面的打印5 matchesScala的正則表達式匹配怪異的行爲

object RegExer extends App { 
val PATTERN = """([5])""".r 

print("5" match { 
case PATTERN(string) => string + " matches!" 
case _ => "No Match!" 
})  
} 

解釋這種打印No Match!

object RegExer extends App { 
val PATTERN = """[5]""".r 

print("5" match { 
case PATTERN(string) => string + " matches!" 
case _ => "No Match!" 
})  
} 

爲什麼範圍的行爲不無parentheseis工作?

回答

0

在第二種情況下,您沒有定義匹配組。這就是括號用於正則表達式匹配的原因:它們定義了應該捕獲的內容(在這種情況下,稍後將其表示爲變量)。

0

您已明確要求返回單個組的模式:PATTERN(string)

string這裏是組(parentheseis in regex)。

您應該使用PATTERN()的模式,而不羣:

"5" match { 
    case string @ PATTERN() => string + " matches!" 
    case _ => "No Match!" 
} 
// String = 5 matches!