3

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.