0

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)

1 Answer 1

5

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

2 Comments

Id suggest you add a condition for the pattern to val Pattern = "([^=]*)=?(.*)".r just in case an empty string is passed in.
@korefn you are right, but it feels safer to keep a strict pattern and use pattern matching to do proper error handling.

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.