0

In some book I've got a code similar to this:

object ValVarsSamples extends App {

  val pattern = "([ 0-9] +) ([ A-Za-z] +)". r   // RegEx

  val pattern( count, fruit) = "100 Bananas"
}

This is supposed to be a trick, it should like defining same names for two vals, but it is not.

So, this fails with an exception.

The question: what this might be about? (what's that supposed to be?) and why it does not work?

-- As I understand first: val pattern - refers to RegEx constructor function.. And in second val we are trying to pass the params using such a syntax? just putting a string

4

2 回答 2

2

这是一个提取器:

val pattern( count, fruit) = "100 Bananas"

这段代码是等价的

val res = pattern.unapplySeq("100 Bananas")
count = res.get(0)
fruit = res.get(1)
于 2013-11-07T19:59:03.437 回答
1

问题是您的正则表达式不匹配,您应该将其更改为:

val pattern = "([ 0-9]+) ([ A-Za-z]+)". r

+ in 之前的空格[ A-Za-z] +表示您匹配类中的单个字符,[ A-Za-z]然后匹配至少一个空格字符。你有同样的问题[ 0-9] +

Scala 正则表达式定义了一个提取器,它在正则表达式中返回一系列匹配组。您的正则表达式定义了两个组,因此如果匹配成功,则序列将包含两个元素。

于 2013-11-07T19:46:15.287 回答