smeeb smeeb - 2 months ago 7
Scala Question

Scala equivalent for 'matches' regex method?

Struggling with my first (ever) Scala regex here. I need to see if a given String matches the regex: "

animal<[a-zA-Z0-9]+,[a-zA-Z0-9]+>
".

So, some examples:

animal<0,sega> => valid
animal<fizz,buzz> => valid
animAl<fizz,buzz> => illegal; animAl contains upper-case (and this is case-sensitive)
animal<fizz,3d> => valid
animal<,3d> => illegal; there needs to be something [a-zA-Z0-9]+ between '<' and ','
animal<fizz,> => illegal; there needs to be something [a-zA-Z0-9]+ between ',' and '>'
animal<fizz,%> => illegal; '%' doesn't match [a-zA-Z0-9]+
etc.


My best attempt so far:

val animalRegex = "animal<[a-zA-Z0-9]+,[a-zA-Z0-9]+>".r
animalRegex.findFirstIn("animal<fizz,buzz")


Unfortunately that's where I'm hitting a brick wall.
findFirstIn
and all the other obvious methods available of
animalRegex
all return
Option[String]
types. I was hoping to find something that returns a boolean, so something like:

val animalRegex = "animal<[a-zA-Z0-9]+,[a-zA-Z0-9]+>".r
if(animalRegex.matches("animal<fizz,buzz>")) {
val leftOperand : String = getLeftOperandSomehow(...)
val rightOperand : String = getRightOperandSomehow(...)
}


So I need the equivalent of Java's
matches
method, and then need a way to access the "left operand" (that is, the value of the first
[a-zA-Z0-9]+
group, which in the current case is "
fizz
"), and then ditto for the right/second operand ("
buzz
"). Any ideas where I'm going awry?

Answer

To be able to extract the matched parts from your string, you'll need to add capture groups to your regex expression, like so (note the parentheses):

val animalRegex = "animal<([a-zA-Z0-9]+),([a-zA-Z0-9]+)>".r

Then, you can use Scala's pattern matching to check for a match and extract the operands from the string:

val str = "animal<fizz,3d>"
val result = str match {
    case animalRegex(op1,op2) => s"$op1, $op2"
    case _                    => "Did not match"
}

In this example, result will contain "fizz, 3d"