Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala capture group using regex

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?

like image 822
Geo Avatar asked Jun 16 '10 05:06

Geo


People also ask

How do you check if a string matches a regex in Scala?

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.

What is regex in Scala?

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.


1 Answers

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).


The lookaround option

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).

References

  • regular-expressions.info/Lookarounds
like image 87
polygenelubricants Avatar answered Oct 07 '22 20:10

polygenelubricants