scala.MatchError: String Extraction using regular expression -


i working on scala pattern matching.

for below program getting output.

   val pattern = "([0-9]+) ([a-za-z]+)".r     val pattern(count,fruit) ="100 bananas" 

the output of program

count: string = 100 fruit: string = bananas

i modified program deeper understanding, adding 1 more numeric pattern pattern val object , 1 more object extraction pattern val.

the program

  val pattern = "([0-9]+) ([a-za-z]+)  ([0-9]+) ".r    val pattern(count, fruit, price) ="100 bananas 1002" 

but program not compiling , throwing error. error -

scala.matcherror: 100 bananas 1002 (of class java.lang.string) @ #worksheet#.x$1$lzycompute(extractingstrings.sc0.tmp:6) @ #worksheet#.x$1(extractingstrings.sc0.tmp:6) @ #worksheet#.count$lzycompute(extractingstrings.sc0.tmp:6) @ #worksheet#.count(extractingstrings.sc0.tmp:6) @ #worksheet#.#worksheet#(extractingstrings.sc0.tmp:6) 

can explain why throwing error. in advance.

the program compiling fine. getting runtime exception (scala.matcherror).

this because second pattern "([0-9]+) ([a-za-z]+) ([0-9]+) " has 2 spaces after ([a-za-z]+) , additional space @ end after ([0-9]+) , 100 bananas 1002 not match patter (one space after bananas , no space after 1002).

remove spaces, change pattern ([0-9]+) ([a-za-z]+) ([0-9]+)" , 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 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -