1
需要提取令牌和固定文本。例如:parboiled2解析器提取令牌和固定文本
「你好{TOKEN1}今天的日期是{token2}你想叫{token3}」
將返回FixedPart("Hello ")
TokenPart(token1)
FixedPart(" today's date is ")
TokenPart(token2)
FixedPart(" would you like to call ")
TokenPart(token3)
這是幼稚的做法
import org.parboiled2.ParserInput
import org.parboiled2.Parser
import org.parboiled2.CharPredicate
sealed trait Part
case class TokenPart(tokenName : String) extends Part
case class FixedPart(text : String) extends Part
class MyParser(val input: ParserInput) extends Parser {
def Token = rule { '{' ~ capture(TokenName) ~> (TokenPart(_)) ~'}' }
//how this should be implemented??
def NotToken = rule { capture (!Token) ~>(FixedPart(_))}
def TokenName = rule { CharPredicate.Alpha ~ oneOrMore (CharPredicate.AlphaNum) }
// This would not work
def TokenNotToken = rule { (Token|NotToken) }
def InputLine = rule { zeroOrMore (TokenNotToken) }
}
object MyParser {
def main(args: Array[String]) {
val res = new MyParser("Hello {token1} today's date is {token2} would you like to call {token3}").InputLine.run() // Success
println(res)
}
}
任何其他實現這個?
請,不叫規則內部的「CharPredicate.NAME」。創建一個變量並分配謂詞的值。在你的代碼中,每當解析器面對規則時,都會評估「CharPredicate.NAME」。它會降低性能。 – ppopoff