scala - Splitting string using Regex and pattern matching throws an exception -


could guys please tell me i'm doing incorrectly trying extract using regex pattern-matching? have following code

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

and following exception in runtime

exception in thread "main" scala.matcherror: key=value (of class java.lang.string) 

that's more of regular expression problem: regex not capture groups, matches single = character.

with

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

you get:

scala> val pattern(key, value) = "key=value" key: string = key value: string = value 

edit:

also, won't match if input string empty. can change pattern make match, or (better) can pattern match regex, so:

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

if wanted split input text whatever regex matches, 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 

Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -