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)

Answers


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

Need Your Help

C++ special instance of template function for some type which is a template class itself

c++ templates instance friend

I got trouble in creating special instance of member template function of non-template class. I have, for example, class A with template member function F:

Is it wrong to use the domain account in IIS?

c# .net iis

I am trying to deploy my webiste on a server.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.