Scala regexps: how to return matches as array or list

后端 未结 3 1498
刺人心
刺人心 2020-12-28 19:53

Is there a simple way to return regex matches as an array?
Here is how I am trying in 2.7.7:

val s = \"\"\"6 1 2\"\"\"
val re = \"\"\"(\\d+)         


        
3条回答
  •  暖寄归人
    2020-12-28 20:35

    There is a difference between how unapplySeq interprets mulitple groups and how findAllIn does. findAllIn scans your pattern over the string and returns each string that matches (advancing by the match if it succeeds, or one character if it fails).

    So, for example:

    scala> val s = "gecko 6 1 2 3 4 5"
    scala> re.findAllIn(s).toList
    res3: List[String] = List(6 1 2, 3 4 5)
    

    On the other hand, unapplySeq assumes a perfect match to the sequence.

    scala> re.unapplySeq(s)
    res4: Option[List[String]] = None
    

    So, if you want to parse apart groups that you have specified in an exact regex string, use unapplySeq. If you want to find those subsets of the string that look like your regex pattern, use findAllIn. If you want to do both, chain them yourself:

    scala> re.findAllIn(s).flatMap(text => re.unapplySeq(text).elements )
    res5: List[List[String]] = List(List(6, 1, 2), List(3, 4, 5))
    

提交回复
热议问题