2015-10-02 117 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