如何使用 FParsec 解析字符串值

Pet*_*ner 3 f# parsing fparsec

如何从另一个字符串中解析出一个简单的字符串。

在 FParsec 教程中给出了以下代码:

let str s = pstring s
let floatBetweenBrackets = str "[" >>. pfloat .>> str "]"
Run Code Online (Sandbox Code Playgroud)

我不想解析支持之间的浮点数,而是解析表达式中的字符串。

某事。喜欢:

Location := LocationKeyWord path EOL

给定一个辅助函数

let test p s =
    match run p s with
    | Success(result,_,_)  -> printfn "%A" result
    | Failure(message,_,_) -> eprintfn "%A" message
Run Code Online (Sandbox Code Playgroud)

和一个解析器函数:let pLocation = ...

当我打电话时test pLocation "Location /root/somepath"

它应该打印"/root/somepath"

我的第一次尝试是将教程代码修改如下:

let pLocation = str "Location " >>. str
Run Code Online (Sandbox Code Playgroud)

但这给了我一个错误:

Error 244   Typeerror. Expected:
    Parser<'a,'b>    
Given:
    string -> Parser<string,'c>  
The type CharStream<'a> doesn't match with the Type string
Run Code Online (Sandbox Code Playgroud)

Lea*_*and 5

str不适用于您的路径,因为它旨在匹配/解析常量字符串。str对于常量效果很好"Location ",但您也需要为路径部分提供解析器。您没有指定可能是什么,因此这里是一个仅解析任何字符的示例。

let path = manyChars anyChar
let pLocation = str "Location " >>. path
test pLocation "Location /root/somepath"
Run Code Online (Sandbox Code Playgroud)

您可能需要为路径使用不同的解析器,例如,它会解析任何字符,直到换行符或文件末尾,以便您可以解析许多行。

let path = many1CharsTill anyChar (skipNewline <|> eof)
Run Code Online (Sandbox Code Playgroud)

您可以制作其他不接受空格或处理带引号的路径等的解析器。