如何从另一个字符串中解析出一个简单的字符串。
在 FParsec 教程中给出了以下代码:
let str s = pstring s
let floatBetweenBrackets = str "[" >>. pfloat .>> str "]"
我不想解析 backets 之间的 float ,而是更多的是表达式中的字符串。
某事。喜欢:
Location := LocationKeyWord 路径 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
最佳答案
str
不适用于您的路径,因为它旨在匹配/解析常量字符串。 str
适用于常量 "Location "
但您还需要为路径部分提供解析器。您没有指定可能是什么,所以这里是一个仅解析任何字符的示例。
let path = manyChars anyChar
let pLocation = str "Location " >>. path
test pLocation "Location /root/somepath"
您可能希望为路径使用不同的解析器,例如,这会解析任何字符,直到换行符或文件结尾,以便您可以解析多行。
let path = many1CharsTill anyChar (skipNewline <|> eof)
您可以制作其他不接受空格或处理引用路径等的解析器。
关于parsing - 如何使用 FParsec 解析字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23611647/