Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a string value using FParsec

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
like image 378
Peter Ittner Avatar asked Jun 19 '26 07:06

Peter Ittner


1 Answers

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.

like image 120
Leaf Garland Avatar answered Jun 21 '26 04:06

Leaf Garland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!