Let's say I have this code:
val string = "one493two483three" val pattern = """two(\d+)three""".r pattern.findAllIn(string).foreach(println)
I expected findAllIn
to only return 483
, but instead, it returned two483three
. I know I could use unapply
to extract only that part, but I'd have to have a pattern for the entire string, something like:
val pattern = """one.*two(\d+)three""".r val pattern(aMatch) = string println(aMatch) // prints 483
Is there another way of achieving this, without using the classes from java.util
directly, and without using unapply?
Scala String matches() method with exampleThe matches() method is used to check if the string stated matches the specified regular expression in the argument or not. Return Type: It returns true if the string matches the regular expression else it returns false.
Regular Expressions explain a common pattern utilized to match a series of input data so, it is helpful in Pattern Matching in numerous programming languages. In Scala Regular Expressions are generally termed as Scala Regex. Regex is a class which is imported from the package scala. util. matching.
Here's an example of how you can access group(1)
of each match:
val string = "one493two483three" val pattern = """two(\d+)three""".r pattern.findAllIn(string).matchData foreach { m => println(m.group(1)) }
This prints "483"
(as seen on ideone.com).
Depending on the complexity of the pattern, you can also use lookarounds to only match the portion you want. It'll look something like this:
val string = "one493two483three" val pattern = """(?<=two)\d+(?=three)""".r pattern.findAllIn(string).foreach(println)
The above also prints "483"
(as seen on ideone.com).
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