3

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

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

let str s = pstring s
let floatBetweenBrackets = str "[" >>. pfloat .>> str "]"

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

某事。像:

Location := LocationKeyWord path EOL

给定一个辅助函数

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

还有一个解析器功能:let pLocation = ...

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

它应该打印"/root/somepath"

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

let pLocation = str "Location " >>. str

但这给了我一个错误:

Error 244   Typeerror. Expected:
    Parser<'a,'b>    
Given:
    string -> Parser<string,'c>  
The type CharStream<'a> doesn't match with the Type string
4

1 回答 1

5

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

let path = manyChars anyChar
let pLocation = str "Location " >>. path
test pLocation "Location /root/somepath"

您可能希望为路径使用不同的解析器,例如,这会解析任何字符,直到换行符或文件结尾,以便您可以解析多行。

let path = many1CharsTill anyChar (skipNewline <|> eof)

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

于 2014-05-12T14:58:43.063 回答