Locked History Actions

scala/Regex

正規表現

参考

正規表現使用上の注意事項

正規表現をmatch式に使う場合は必ず_*引数をつける(少なくとも最後の引数として)

object RegEx {

  val PATTERN = """^[A-Z]+$""".r
  val pattern = """^[A-Z]+$""".r
  
  def main(args: Array[String]) {
    println("ABC" match { // 1
      case PATTERN => "matched"
      case _ => "unmatched"
    })
    println("ABC" match { // 2
      case PATTERN(_*) => "matched"
      case _ => "unmatched"
    })
    println("ABC" match { // 3
      case pattern => "matched"
      //case _ => "unmatched"
    })    
    println("ABC" match { // 4
      case pattern(_*) => "matched"
      case _ => "unmatched"
    })
  }
}

上記の実行結果は

unmatched
matched
matched
matched