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?
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.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With