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

Parsec search : 文字列中のパターンとマッチ

Parsec のパーサは、プログラム言語の構文解析が目的なので、パーサは文字列の先頭から始まるパターンにしかマッチしない。しかし、正規表現のように文字列の中ほどのパターンにマッチしてくれるパーサがないと不便だ。そこで、パーサ expr が文字列の中ほどにあってもマッチするようなパターンをつくるパーサ・コンビネータ search を作ってみた。定義は次のようになる。

ghci> let search expr = try (expr) <|> do {anyChar; search expr}

実行例:
Prelude> :m Text.ParserCombinators.Parsec
Prelude Text.ParserCombinators.Parsec> :set prompt "ghci> "
ghci> let search expr = expr <|> do {anyChar; search expr}
ghci> parseTest (search (string "world")) "hello, world"
"world"
ghci> parseTest (search (char 'w')) "hello, world"
'w'
ghci> parseTest (search (string "nothing")) "hello, world"
parse error at (line 1, column 13):
unexpected end of input

これで、安心して正規表現から Parsec へ移行できる。
by tnomura9 | 2011-11-29 04:43 | Haskell | Comments(0)
<< Parsec replaceM... Parsec いろいろなパターン >>