Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pattern match in scala 2.13?

I have the following regex, that I would like to pattern match in Scala 2.13.
The regex:

\/brokers\/ids\/\d{1,}$

The following string, that is going to be validate:

scala> ("echo dump" #| "nc localhost 32773" #| "grep brokers").!!
res2: String =
"       /brokers/ids/1
"

How can I do it in Scala 2.13?

like image 585
softshipper Avatar asked Jul 18 '19 07:07

softshipper


People also ask

Does Scala have pattern matching?

Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case.

How does Scala pattern matching work?

Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. It is a more powerful version of the switch statement in Java and it can likewise be used in place of a series of if/else statements.

What is pattern matching command?

Pattern matching is used by the shell commands such as the ls command, whereas regular expressions are used to search for strings of text in a file by using commands, such as the grep command.

What is pattern matching explain with example?

Pattern matching is the process of checking whether a specific sequence of characters/tokens/data exists among the given data. Regular programming languages make use of regular expressions (regex) for pattern matching.


1 Answers

Scala 2.13 introduced interpolated string patterns, so you could avoid using regex and just do:

"/brokers/ids/1" match {
  case s"/brokers/ids/$ids" => ids //returns 1
}
like image 104
Krzysztof Atłasik Avatar answered Sep 26 '22 21:09

Krzysztof Atłasik