4

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.

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

4 Comments

I have changed the pattern as you have suggested. It is not working.
val pattern = "([0-9]+) ([A-Za-z]+) ([0-9]+)".r
@RajkumarNatarajan no problem, if you have any other doubts please edit your question. Otherwise please accept this answer so other people know this question was already solved.
Accepted your answer. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.