Skip to content

Instantly share code, notes, and snippets.

@munro
Created July 18, 2014 21:13
Show Gist options
  • Save munro/c85d622929de414fb0e1 to your computer and use it in GitHub Desktop.
Save munro/c85d622929de414fb0e1 to your computer and use it in GitHub Desktop.
-- | Parse string
-- >>> parse (parseString) "fail" "\"hello 'world' foobar\""
-- Right (String "hello 'world' foobar")
-- >>> parse (parseString) "fail" "\"hello \\\"world' \n\r \\\\ foobar\""
-- Right (String "hello \"world' \n\r \\ foobar")
parseString :: GenParser Char st Word
parseString = do char '"'
x <- many $ chars
char '"'
return $ String x
where chars = escaped <|> noneOf "\""
escaped = char '\\' >> choice (zipWith escapedChar codes replacements)
escapedChar code replacement = char code >> return replacement
codes = ['b', 'n', 'f', 'r', 't', '\\', '\"', '/']
replacements = ['\b', '\n', '\f', '\r', '\t', '\\', '\"', '/']
tryEscaped c = try $ char '\\' >> char (fst c) >> return (snd c)
escapedChars = zip "bnfrt\\\"/" "\b\n\f\r\t\\\"/"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment