例如,我想从"abc"
获取"aabbccabc"
,这应该很容易使用正则表达式。但我想使用parsec。似乎try
可以做到这一点,但这一定效率很低......
我试过了:
import Text.ParserCombinators.Parsec
ps pser txt = case (parse pser "" txt ) of
Left e -> show e
Right v -> v
并得到以下结果:
λ> ps (string "asf") " dsfdsasf"
"(line 1, column 1):\nunexpected \" \"\nexpecting \"asf\""
答案 0 :(得分:4)
您可以这样做:
{-# LANGUAGE FlexibleContexts #-}
import Text.Parsec
import Text.Parsec.Char
findSubString str = try (string str) <|> (anyChar *> findSubString str)
foo = do
findSubString "abc"
findSubString "def"
test1 = parseTest foo "this is abc" -- fails: expecting def
test2 = parseTest foo "this is abc and de" -- fails: expecting def
test3 = parseTest foo "this is abc and def" -- succeeds