Scala-解析字符串直到字符串结束
使用scala解析器组合器,我想尝试使用后缀字符串(Scala-解析字符串直到字符串结束,scala,parsing,parser-combinators,Scala,Parsing,Parser Combinators,使用scala解析器组合器,我想尝试使用后缀字符串(end)进行解析。但是前面的解析器没有结束内容。如何修复它? (只是更改“[^z]”。r不是好答案。) val input=“aaabbbzzz” parseAll(body,input)//java.lang.IllegalStateException:'zzz'应为'zzz',但找到了源代码结尾 def body:Parser[List[String]=content.+…检查content.+与否 另一种解决方法是使用notcombina
end
)进行解析。但是前面的解析器没有结束内容。如何修复它?
(只是更改“[^z]”。r不是好答案。)
val input=“aaabbbzzz”
parseAll(body,input)//java.lang.IllegalStateException:'zzz'应为'zzz',但找到了源代码结尾
def body:Parser[List[String]=content.+…检查content.+与否 另一种解决方法是使用not
combinator。您只需要检查您正在解析的不是end
值
诀窍是not
不消耗输入,因此如果not(end)
成功(意味着end
失败),那么我们没有达到停止条件,因此我们可以使用内容解析器解析导致end
解析器失败的三个字符
与注释中链接的非贪婪方法一样,对于输入中“zzz”后面有字符的输入(例如“aaabbbzzzzzz”
),它将失败
但是对于您的用例来说,它可能已经足够了。所以你可以试一试
与:
def body:Parser[List[String]=rep(not(end)~>content)这个怎么样?使用noneGreedy
,上面的例子就足够了,谢谢:)我注意到我问题中的底部模式写得很简单def模式:解析器[String]=“”(.*)(?=zzz)“”.r^^{case text=>parseAll(另一个,text).
@krrrr38:请用您遇到的两种解决方案回答您自己的问题,并接受它。
val input = "aaabbbzzz"
parseAll(body, input) // java.lang.IllegalStateException: `zzz' expected but end of source found
def body: Parser[List[String]] = content.+ <~ end
def content: Parser[String] = repChar // more complex like (repChar | foo | bar)
def repChar: Parser[String] = ".{3}".r // If change this like "[^z]{3}", but no flexibility.
def end: Parser[String] = "zzz"
"""(.*)(?=zzz)""".r.into(str => ...check content.+ or not... <~ end)
def body: Parser[List[String]] = rep(not(end) ~> content) <~ end