我正在尝试使用FParsec实现一个空格敏感的解析器,我开始定义一个函数,它将解析以n
空格字符开头的文本行。
这是我到目前为止所拥有的:
let test: Parser<string list,int>
= let manyNSatisfy i p = manyMinMaxSatisfy i i p
let p = fun (stream:CharStream<int>) ->
let state = stream.UserState
// Should fail softly if `state` chars wasn't parsed
let result = attempt <| manyNSatisfy state (System.Char.IsWhiteSpace) <| stream
if result.Status <> Ok
then result
else restOfLine false <| stream
sepBy p newline
我的问题是,当我跑
时 runParserOnString test 1 "test" " hi\n there\nyou" |> printfn "%A"
我收到“你”的错误。我的印象是attempt
会回溯任何状态更改,并返回Error
,因为我的状态会让我软失败。
如何从解析器中获取["hi"; "there"]
?
答案 0 :(得分:3)
我想要sepEndBy
,也就是说我应该终止分隔符上的解析。
答案 1 :(得分:0)
这看起来更惯用。我有硬编码1
,但很容易将其作为参数提取。
let skipManyNSatisfy i = skipManyMinMaxSatisfy i i
let pMyText =
( // 1st rule
skipManyNSatisfy 1 System.Char.IsWhiteSpace // skip an arbitrary # of WhiteSpaces
>>. restOfLine false |>> Some // return the rest as Option
)
<|> // If the 1st rule failed...
( // 2nd rule
skipRestOfLine false // skip till the end of the line
>>. preturn None // no result
)
|> sepBy <| newline // Wrap both rules, separated by newLine
|>> Seq.choose id // Out of received string option seq, select only Some()