Parser for Quoted string using Parsec

This is what I would do:

escape :: Parser String
escape = do
    d <- char '\\'
    c <- oneOf "\\\"0nrvtbf" -- all the characters which can be escaped
    return [d, c]

nonEscape :: Parser Char
nonEscape = noneOf "\\\"\0\n\r\v\t\b\f"

character :: Parser String
character = fmap return nonEscape <|> escape

parseString :: Parser String
parseString = do
    char '"'
    strings <- many character
    char '"'
    return $ concat strings

Now all you need to do is call it:

parse parseString "test" "\"this is \\\"test \\\" message \\\"sample\\\" text\""

Parser combinators are a bit difficult to understand at first, but once you get the hang of it they are easier than writing BNF grammars.


quotedString = do
    char '"'
    x <- many (noneOf "\"" <|> (char '\\' >> char '\"'))
    char '"'
    return x

I believe, this should work.


In case somebody is looking for a more out of the box solution, this answer in code-review provides just that. Here is a complete example with the right imports:

import           Text.Parsec
import           Text.Parsec.Language
import           Text.Parsec.Token

lexer :: GenTokenParser String u Identity
lexer = makeTokenParser haskellDef

strParser :: Parser String
strParser = stringLiteral lexer

parseString :: String -> Either ParseError String
parseString = parse strParser ""