2016-02-21 9 views
-2

我要分析此字符串:"er1r2r3"有:"""(e|w|n|s)(r[1-3])*""".r斯卡拉字符串模式匹配的正則表達式的明星多findallin

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)

只修正這個,正則表達式。

+0

必須用'(E | W | N | S | R [1-3 ])而不是。 –

回答

0

我不認爲這是可以修復的'只適用於正則表達式'(無論這應該是什麼意思),因爲代碼在使用第一個正則表達式之前失敗。

由於您在空的String上致電apply(index: Int)而失敗。所以,要麼你叫str(0)甚至parseSidedPieces之前做一個isEmpty檢查,或更改代碼,並匹配整個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))