문제

How do I parse a simple string out of another string.

In the FParsec Tutorial there is the following code given:

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

I don't want to parse a float between backets but more a string within an expression.

Sth. Like:

Location := LocationKeyWord path EOL

Given a helper function

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

And a parser-function: let pLocation = ...

When I call test pLocation "Location /root/somepath"

It should print "/root/somepath"

My first attempt was to modify the tutorial code as the following:

let pLocation = str "Location " >>. str

But this gives me an error:

Error 244   Typeerror. Expected:
    Parser<'a,'b>    
Given:
    string -> Parser<string,'c>  
The type CharStream<'a> doesn't match with the Type string
도움이 되었습니까?

해결책

str doesn't work for your path because it is designed to match/parse a constant string. str works well for the constant "Location " but you need to provide a parser for the path part too. You don't specify what that might be so here is an example that just parses any characters.

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

You might want to a different parser for the path, for example this parses any characters until a newline or end of file so that you could parse many lines.

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

You could make other parsers that don't accept spaces or handle quoted paths, etc.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top