[Haskell-beginners] Parsec, parsing 'free text'

Stephen Tetley stephen.tetley at gmail.com
Sun Mar 11 11:53:50 CET 2012


Hi Franco

Actually the simple case of finding formatting tags in free text was
easier in Parsec than my email last night suggested. Perhaps it is
artificially easy because you can identify tag start and ends with a
single character so you can use `satisfy`.

import Text.Parsec
import Text.Parsec.String
import Control.Applicative hiding ( (<|>), many )


data Text1 = FreeText String | Formatted String
  deriving (Eq,Ord,Show)

type Text = [Text1]

runText :: String -> Either ParseError Text
runText = runP lexer () "no-input"


notLAngle :: Char -> Bool
notLAngle = (/= '<')

notRAngle :: Char -> Bool
notRAngle = (/= '>')

lexer :: Parser Text
lexer = many (formatted <|> free)

formatted :: Parser Text1
formatted = Formatted <$>
    between (char '<') (char '>') (many1 (satisfy notRAngle))

free :: Parser Text1
free = FreeText <$> many1 (satisfy notLAngle)



demo01 = runText "[ someconditions | this is some <red - formatted> text.]"
demo02 = runText "<red - formatted> more text."



More information about the Beginners mailing list