2015-10-02 121 views
2

例如,我想从"aabbccabc"获得​​,使用正则表达式应该很容易。但我想使用parsec。看来,try能做到这一点,但是这必须是非常低效的...使用parsec在字符串中查找子字符串

我想:

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

* [...]我想从''aabbccabc'''得到''abc''[*] *您是什么意思? – Jubobs

回答

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 
+0

工作,但使用尝试,它利用回溯。用大文件这将是不合适的? – doofin

+2

我想你应该解释为什么你想使用parsec来搜索大文件中的字符串。为什么parsec?为什么不只是'Data.Text'中的'breakOn'? – ErikR

+0

因为我可能将解析工作扩展到更复杂的工作,breakOn是一个很好的建议 – doofin