1

Can someone explain to me why is this happening,

val p = """[0-1]""".r "1" match { case p => print("ok")} //returns ok, Good result "4dd" match { case p => print("ok")} //returns ok, but why? 

I also tried:

"14dd" match { case p => print("ok") case _ => print("non")} //returns ok with: warning: unreachable code 

1 Answer 1

2

You'll find the answer if you try to add a new option:

"4dd" match { case p => print("ok") case _ => print("ko") } <console>:24: warning: patterns after a variable pattern cannot match (SLS 8.1.1) "4dd" match { case p => print("ok"); case _ => print("ko")} 

You are matching against a pattern without extract any value, the most common use of regex is, afaik, to extract pieces of the input string. So you should define at least one extraction by surrounding it with parenthesis:

val p = """([0-1])""".r 

And then match against each of the extraction groups:

So this will return KO

scala> "4dd" match { | case p(item) => print("ok: " + item) | case _ => print("ko") | } ko 

And this will return OK: 1

scala> "1" match { | case p(item) => print("ok: " + item) | case _ => print("ko") | } ok: 1 
Sign up to request clarification or add additional context in comments.

3 Comments

What is exactly item ?
item represents the matching part of your input string (in your example the whole string). But imagine you can split a number between the integer and the decimal part, your regex will looks as follow: """([0-1])\.([0-1])""" and the case will be p(integer, decimal)
Thank you so much for your answer and explanations!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.