Reputation: 10143
I am working on scala pattern matching.
For the below program I am getting output.
val pattern = "([0-9]+) ([A-Za-z]+)".r
val pattern(count,fruit) ="100 bananas"
The output of the program is
count: String = 100 fruit: String = bananas
I modified the program to get deeper understanding, by adding one more numeric pattern into the pattern val object and one more object into the extraction pattern val.
The program is
val pattern = "([0-9]+) ([A-Za-z]+) ([0-9]+) ".r
val pattern(count, fruit, price) ="100 bananas 1002"
But the program is not compiling and it is throwing error. The error is -
scala.MatchError: 100 bananas 1002 (of class java.lang.String)
at #worksheet#.x$1$lzycompute(ExtractingStrings.sc0.tmp:6)
at #worksheet#.x$1(ExtractingStrings.sc0.tmp:6)
at #worksheet#.count$lzycompute(ExtractingStrings.sc0.tmp:6)
at #worksheet#.count(ExtractingStrings.sc0.tmp:6)
at #worksheet#.#worksheet#(ExtractingStrings.sc0.tmp:6)
Can anyone explain why it is throwing this error. Thanks in advance.
Upvotes: 4
Views: 1970
Reputation: 15141
The program is compiling just fine. What you are getting is a runtime exception (scala.MatchError).
This is because your second pattern "([0-9]+) ([A-Za-z]+) ([0-9]+) "
has 2 spaces after ([A-Za-z]+)
and an additional space at the end after ([0-9]+)
and 100 bananas 1002
does not match that patter (one space after bananas
and no space after 1002
).
Remove those spaces, change the pattern into ([0-9]+) ([A-Za-z]+) ([0-9]+)"
and it will work.
scala> val pattern = "([0-9]+) ([A-Za-z]+) ([0-9]+)".r
pattern: scala.util.matching.Regex = ([0-9]+) ([A-Za-z]+) ([0-9]+)
scala> val pattern(count, fruit, price) ="100 bananas 1002"
count: String = 100
fruit: String = bananas
price: String = 1002
Upvotes: 6