人気ブログランキング | 話題のタグを見る

Parsec マッチした全ての文字列を取得 getMatchAll

文字列から、記述したパターンにマッチするもの全てを取得する関数 getMatchAll を作ってみた。

実行例:
*Match> getMatchAll (string "ap") "apple juice, bad apple"
Just ["ap","ap"]
*Match> getMatchAll (do m <- string "a"; n <- count 1 anyChar; return (m++n)) "apple juice, bad apple"
Just ["ap","ad","ap"]

ソース:
import Text.ParserCombinators.Parsec

getMatchAll expr line =
  case parse getAllParser "" line of
    Left _ -> Nothing
    Right x -> Just x
  where
    get1Parser = try (expr) <|> do {anyChar; get1Parser}
    getAllParser = do
        n <- get1Parser
        m <- try (getAllParser) <|> do {many anyChar; return []}
        return ([n] ++ m)
by tnomura9 | 2011-12-01 13:16 | Haskell | Comments(0)
<< 愛川こずえ Parsec を正規表現がわりに使う >>