Scala regexps: how to return matches as array or list

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

    Try this:

      val s = """6 1 2"""
      val re = """\d+""".r
      println(re.findAllIn(s).toList) // List(6, 1, 2)
      println(re.findAllIn(s).toList.length) // 3
    

    And, if you really need a list of the match groups within a singe Regex:

      val s = """6 1 2"""
      val Re = """(\d+)\s(\d+)\s(\d+)""".r
      s match {  // this is just sugar for calling Re.unapplySeq(s)
          case Re(mg@_*) => println(mg) // List(6, 1, 2)
      }
    

提交回复
热议问题