scala - Regex parse a list of comma separated number ranges, and capture them in individual groups -
i found the following regex matching comma separated numbers or ranges of numbers:
val reg = """^(\d+(-\d+)?)(,\s*(\d+(-\d+)?))*$""".r
while does match valid strings, one string out of it, instead of a list of strings, each corresponding 1 of separated entries. e.g.
reg.findallin("1-2, 3").map(s => s""""$s"""").tolist
gives
list("1-2, 3")
but want:
list("1-2", "3")
the following comes closer:
val list = "1-2, 3" match { case reg(groups @ _*) => groups case _ => nil } list.map(s => s""""$s"""")
but contains sorts of 'garbage':
list("1-2", "-2", ", 3", "3", "null")
with findallin
should not try match entire string. split biggest continuos match can find. instead need part of regex:
val reg = """(\d+(-\d+)?)""".r
if use findallin
return need.
scala> val x = """(\d+(-\d+)?)""".r x: scala.util.matching.regex = (\d+(-\d+)?) scala> x.findallin("1-2, 3").tolist res0: list[string] = list(1-2, 3)
Comments
Post a Comment