Scala字符串模式匹配正则表达式星形多个findallin

时间:2016-02-21 11:10:15

标签: regex scala

我想用"er1r2r3"

解析此字符串:"""(e|w|n|s)(r[1-3])*""".r
  val SideR = """(e|w|n|s)""".r

  val PieceR = """(r)([1-3])""".r

  def parseSidedPieces(str: String): (Char, List[Char]) = {
    val side = str(0) match {
      case SideR(s) => s
    }

    val pieces = parsePieces(str.tail)

    (side, pieces)
  }

  def parsePieces(str: String): List[Char] = {
    PieceR.findAllIn(str).toList map {
      case PieceR(c, n) => n
    }
  }

但这会引发空字符串"",因为str(0)

修复此问题,仅限正则表达式。

1 个答案:

答案 0 :(得分:0)

我认为这不能解决,只有正规用户才能解决这个问题。 (不管是什么意思),因为代码在使用第一个正则表达式之前就失败了。

失败是因为您在空apply(index: Int)上致电String。因此,您可以在致电isEmpty甚至str(0)之前进行parseSidedPieces检查,或者更改代码并匹配整个String

val PieceR = """(r)([1-3])""".r
val CombinedR = "(e|w|n|s)((?:r[1-3])*)".r

def parseSidedPieces(str: String): (Char, List[Char]) = {
  str match {
    case CombinedR(side, pieces) =>
      (side(0), parsePieces(pieces))
    case "" => 
      // hmm, what kind of tuple would be a good return value here? maybe:
      throw new IllegalArgumentException(s"Unexpected input: $str")
    case _ =>
      // handle unmatched strings however you like, I'd do:
      throw new IllegalArgumentException(s"Unexpected input: $str")
  }
}

def parsePieces(str: String): List[Char] = {
  PieceR.findAllIn(str).toList map {
    case PieceR(c, n) => n(0)
  }
}

parseSidedPieces("er1r2r3") |-> res0: (Char, List[Char]) = (e,List(1, 2, 3))