smeeb smeeb - 24 days ago 4x
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: "


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]+

My best attempt so far:

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

Unfortunately that's where I'm hitting a brick wall.
and all the other obvious methods available of
all return
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
method, and then need a way to access the "left operand" (that is, the value of the first
group, which in the current case is "
"), and then ditto for the right/second operand ("
"). Any ideas where I'm going awry?


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"