2
我試圖讓下面的工作。所以我有括號內的字符串。字符串可以包含任何字符,因此我想要解析的字符串也可以包含括號。我認爲當前正則表達式也匹配最後一個應該與<〜「)」匹配的括號,因此解析失敗。我在這裏錯過了什麼?解析包含任何字符的字符串
private def parser: Parser[Any] = a ~ b ~ c ^^ {
<do stuff here>
}
private def a: Parser[String] = "\"[^\"]*\"".r | "[^(),>]*".r
private def b: Parser[String] = opt("(" ~> ".*".r <~ ")") ^^ {
case Some(y) => y.trim
case None => ""
}
private def c: Parser[String] = rep("[email protected]" ~> "[^>.]*".r) ^^ (new String(_).trim)
這應該分析以下類型的字符串:
test0
[email protected]
"test2"
"test3"[email protected]
test4..
[email protected]
"test6.."[email protected]
"[email protected]"[email protected]
test8(icl>uw)
test9(icl>uw)[email protected]
"test10..()[email protected]"(icl>uw)[email protected]
test11(icl>uw(agt>uw2,obj>uw3),icl>uw4(agt>uw5))
test12(icl>uw1(agt>uw2,obj>uw3),icl>uw4)[email protected]@attr2
test13(agt>thing,obj>role>effect)
因此,「一」解析器解析字符串,直到開括號或@ ATTR部分。 「b」解析器解析可選圓括號內的字符。 「c」分析可選的。@ attrs。
目前,我得到一個包含所有測試串類似的錯誤括號部分:
11:07:44.662 [main] DEBUG - Parsed: test8()
11:07:44.667 [main] ERROR - FAILURE parsing: test8(icl>uw) -- `)' expected but `i' found
所以我假設分析器正確分析的第一部分,但未能當它看到括號部分。
你需要擴大與(也許是)一個小**例如這個問題你**正在努力去做,那是不是在起作用,因爲目前形成的問題尚不清楚。 例如:得到字符串輸入時會發生什麼?(()'?發生了什麼?出錯?有什麼意外? – 2012-04-23 19:14:13
讓示例更清楚一點。因此,本質上我想解析括號內的任何內容 – Kitanotori 2012-04-24 10:54:22
正則語言(以及正則表達式)不能用於解析嵌套圓括號:它們表達不夠充分,需要使用另一種技術,使用遞歸或自動機或解析器生成器。 – esope 2012-05-23 23:00:27