Created
January 14, 2018 03:02
-
-
Save yuanwang-wf/76d13063d70840edfa97dc95aae7b563 to your computer and use it in GitHub Desktop.
Parsec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module CSVParse (parseCSV) where | |
import Text.ParserCombinators.Parsec | |
-- verbose version | |
-- csvFile :: GenParser Char st [[String]] | |
-- csvFile = do | |
-- do result <- many line | |
-- eof | |
-- return result | |
-- line :: GenParser Char st [String] | |
-- line = do | |
-- do result <- cells | |
-- eol | |
-- return result | |
-- cells :: GenParser Char st [String] | |
-- cells = | |
-- do first <- cellContent | |
-- next <- remainingCells | |
-- return (first : next) | |
-- cellContent :: GenParser Char st String | |
-- cellContent = | |
-- many (noneOf ",\n") | |
-- remainingCells :: GenParser Char st [String] | |
-- remainingCells = do | |
-- (char ',' >> cells) | |
-- <|> (return []) | |
-- -- eol :: GenParser Char st Char | |
-- -- eol = char '\n' | |
eol = char '\n' >> (return ()) | |
csvFile = endBy line eol | |
line = sepBy cell (char ',') | |
cell = many (noneOf ",\n") | |
parseCSV :: String -> Either ParseError [[String]] | |
parseCSV = parse csvFile "(unknown)" | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module FormParse where | |
import Numeric (readHex) | |
import Text.ParserCombinators.Parsec | |
p_query :: CharParser () [(String, Maybe String)] | |
p_query = p_pair `sepBy` char '&' | |
p_pair :: CharParser () (String, Maybe String) | |
p_pair = do | |
name <- many1 p_char | |
value <- optionMaybe (char '=' >> many p_char) | |
return (name, value) | |
p_char :: CharParser () Char | |
p_char = oneOf urlBaseChars | |
<|> (char '+' >> return ' ') | |
<|> p_hex | |
urlBaseChars = ['a'..'z']++['A'..'Z']++['0'..'9']++"$-_.!*'()," | |
p_hex :: CharParser () Char | |
p_hex = do | |
char '%' | |
a <- hexDigit | |
b <- hexDigit | |
let ((d, _):_) = readHex [a,b] | |
return . toEnum $ d | |
parseUrlQuery = parse p_query "(unknown)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment