使用 parsec 在字符串中查找子字符串
Find substring in a string with parsec
例如,我想从 "aabbccabc"
得到 "abc"
,使用正则表达式应该很容易。但我想使用秒差距。好像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\""
你可以这样做:
{-# 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
例如,我想从 "aabbccabc"
得到 "abc"
,使用正则表达式应该很容易。但我想使用秒差距。好像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\""
你可以这样做:
{-# 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