TheM00s3 TheM00s3 - 1 month ago 7
Scala Question

scala regex multiple integers

I have the following string that I would like to match on:

1-10 employees
.

Here is my regex statement
val regex = ("\\d+").r


The problem I have is Im trying to find a way to extract the matched data and determine which value returned is bigger.

Here is what IM doing to process it

def setMinAndMaxValue(currentCompany: CurrentCompany, matchIterator: Iterator[Regex.Match]): CurrentCompany = {
var max = 0
println(s"matchIterator - $matchIterator")
matchIterator.collect {
case regex(s: String) => println("found string")
case regex(IntConv(x)) =>
println("regex case")
if (x > max) max = x
}
val (minVal, maxVal) = rangesForMaxValue(max)
val newDetails = currentCompany.details.copy(minSize = Some(minVal), maxSize = Some(maxVal))
currentCompany.copy(details = newDetails)
}

object IntConv {
def unapply(s : String) : Option[Int] = Try {
Some(s.toInt)
}.toOption.flatten
}

Answer

I thought I was confused by your original question, then you clarified it with code and now I have no idea what you're trying to do.

To extract numbers from a string, try this.

val re = """(\d+)""".r
val nums = re.findAllIn(string_with_numbers).map(_.toInt).toList

Then you can just nums.min, and nums.max, and whatever number processing you need.