expert
expert

Reputation: 30135

Splitting string using Regex and pattern matching throws an exception

Could you guys please tell me what I'm doing incorrectly trying to extract using regex pattern-matching? I have following code

val Pattern = "=".r
val Pattern(key, value) = "key=value"

And I get following exception in runtime

Exception in thread "main" scala.MatchError: key=value (of class java.lang.String)

Upvotes: 0

Views: 1890

Answers (1)

gourlaysama
gourlaysama

Reputation: 11280

That's more of a regular expression problem: your regex does not capture any groups, it just matches a single = character.

With

val Pattern = "([^=]*)=(.*)".r

you will get:

scala> val Pattern(key, value) = "key=value"
key: String = key
value: String = value

Edit:

Also, that won't match if the input string is empty. You can change the pattern to make it match, or (better) you can pattern match with the regex, like so:

"key=value" match {
   case Pattern(k, v) => // do something 
   case _ => // wrong input, do nothing
}

If what you actually wanted was to split the input text with whatever the regex matches, that is also possible using Regex.split:

scala> val Pattern = "=".r
Pattern: scala.util.matching.Regex = =

scala> val Array(key, value) = Pattern.split("key=value")
key: String = key
value: String = value

Upvotes: 5

Related Questions