Scala regexps: how to return matches as array or list

后端 未结 3 1497
刺人心
刺人心 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:26

    Ok, first of all, understand that findAllIn returns an Iterator. An Iterator is a consume-once mutable object. ANYTHING you do to it will change it. Read up on iterators if you are not familiar with them. If you want it to be reusable, then convert the result of findAllIn into a List, and only use that list.

    Now, it seems you want all matching groups, not all matches. The method findAllIn will return all matches of the full regex that can be found on the string. For 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 that there are two matches, and neither of them include the ", " at the middle of the string, since that's not part of any match.

    If you want the groups, you can get them like 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, like 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 will make an Iterator that returns Match instead of String.

提交回复
热议问题