regex - Scala regexps: how to return matches as array or list -
is there simple way return regex matches array?
 here how trying in 2.7.7:
val s = """6 1 2""" val re = """(\d+)\s(\d+)\s(\d+)""".r (m <- re.findallin (s)) println (m) // prints "6 1 2" re.findallin (s).tolist.length // 3? no! returns 1!   but tried:
s match {   case re (m1, m2, m3) => println (m1) }   and works fine! m1 6, m2 1, etc.
then found added confusion:
val mit = re.findallin (s) println (mit.tostring) println (mit.length) println (mit.tostring)   that prints:
non-empty iterator 1 empty iterator   the "length" call somehow modifies state of iterator. going on here?
ok, first of all, understand findallin returns iterator. iterator consume-once mutable object. change it. read on iterators if not familiar them. if want reusable, convert result of findallin list, , use list.
now, seems want matching groups, not matches. method findallin return matches of full regex can found on string. example:
scala> val s = """6 1 2, 4 1 3""" s: java.lang.string = 6 1 2, 4 1 3  scala> val re = """(\d+)\s(\d+)\s(\d+)""".r re: scala.util.matching.regex = (\d+)\s(\d+)\s(\d+)  scala> for(m <- re.findallin(s)) println(m) 6 1 2 4 1 3   see there 2 matches, , neither of them include ", " @ middle of string, since that's not part of match.
if want groups, can them this:
scala> val s = """6 1 2""" s: java.lang.string = 6 1 2  scala> re.findfirstmatchin(s) res4: option[scala.util.matching.regex.match] = some(6 1 2)  scala> res4.get.subgroups res5: list[string] = list(6, 1, 2)   or, using findallin, this:
scala> val s = """6 1 2""" s: java.lang.string = 6 1 2  scala> for(m <- re.findallin(s).matchdata; e <- m.subgroups) println(e) 6 1 2   the matchdata method make iterator returns match instead of string.
Comments
Post a Comment