Skip to content

Instantly share code, notes, and snippets.

@takeouchida
Last active June 3, 2018 14:20
Show Gist options
  • Save takeouchida/9845206 to your computer and use it in GitHub Desktop.
Save takeouchida/9845206 to your computer and use it in GitHub Desktop.

Attoparsec Cheatsheet (vs. Regex)

Preconditions

  • OverloadedString extension is applied.
  • The following modules are imported.
    • Control.Applicative
    • Data.Attoparsec.Text
    • Data.Char

Cheatsheet

Regex Attoparsec Type
. anyChar Parser Char
x char 'x' Parser Char
foo string "foo" Parser Text
x* many' (char 'x') Parser [Char]
x* takeWhile (== 'x') Parser Text
x* skipMany (char 'x') Parser ()
x+ many1 (char 'x') Parser [Char]
x+ takeWhile1 (== 'x') Parser Text
x+ skipMany1 (char 'x') Parser ()
x? `fmap Just (char 'x') < > pure Nothing`
[^x] notChar 'x' Parser Char
[^x]* takeWhile (/= 'x') Parser Text
[x-z] satisfy (inClass "x-z") Parser Char
[^x-z] satisfy (notInClss "x-z") Parser Char
[x-z]* takeWhile (inClass "x-z") Parser Text
(foo|bar) string "foo" <|> string "bar" Parser Text
(foo|bar) choice (map string ["foo", "bar"]) Parser Text
(foo|bar) eitherP (string "foo") (string "bar") Parser (Either Text Text)
(foo){3} count 3 (string "foo") Parser [Text]
foo(,foo)* string "foo" `seqBy` char ',' Parser [Text]
\s space Parser Char
\s skipSpace Parser ()
\S satisfy (not . isSpace) Parser Char
\w satisfy (inClass "_a-zA-Z0-9") Parser Char
\W satisfy (notInClass "_a-zA-Z0-9") Parser Char
\d digit Parser Char
\D satisfy (not . isDigit) Parser Char
\d+ decimal Integral a => Parser a
double Parser Double
[0-9a-fA-F] hexadecimal (Integral a, Bits a) => Parser a

Example

{-# LANGUAGE OverloadedStrings #-}

import Data.Attoparsec.Text
import Prelude hiding (takeWhile)

parseCsvLine = parseOnly (takeWhile (/= ',') `sepBy` char ',')

main = print $ parseCsvLine "aaa,bbb,ccc"
$ runghc attoparsecexample.hs
Right ["aaa","bbb","ccc"]
$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment