I am bit confused with _ * usage in the below example.It is behaving differently and I am completely lost in figuring this out .
val p1="scala".r
val p2="([0-9]+[.]?[0-9]*|[.][0-9]+)$".r
"scala" match {case p1(_) => true case _ => false } // return false
"scala" match {case p1(_ *) => true case _ => false } // return true
"9" match {case p2(_) => true case _ => false} // return true
Thanks in Advance.
The match
needs at least one capture group in the pattern because you are using case(_)
. This is because "match-case" uses unapplySeq(target: Any): Option[List[String]]
, which returns the capture group values, and you require 1 captured value to be present with _
. With _ *
, you ignore this requirement. See Scala regex reference :
To check only whether the Regex matches, ignoring any groups, use a sequence wildcard :
"2004-01-20" match { case date(_*) => "It's a date!" }
Your p2
contains a capturing group, hence the last line returns true.
Your p1
does not contain a capturing group, hence the first match
fails. The second does not since you disabled this requirement with *
.
As an alternative, you can use case p1()
with your first line (the _
representing the obligatory first capture group is removed here), and it will work, too:
"scala" match {case p1() => true case _ => false }) // return true
See this IDEONE demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.