环境
我需要在某个没有空格的 .txt 文件中找到第一次出现的单词。以下是可能的情况:
-- * should succed
t1 = "hello\t999\nworld\t\900"
t2 = "world\t\900\nhello\t999\n"
t3 = "world world\t\900\nhello\t999\n"
-- * should fail
t4 = "world\t\900\nhello world\t999\n"
t5 = "hello world\t999\nworld\t\900"
t6 = "world hello\t999\nworld\t\900"
现在 t6 正在成功,即使它应该失败,因为我的解析器会消耗任何字符,直到它到达 hello。这是我的解析器:
我的解决方案
import Control.Applicative
import Data.Attoparsec.Text.Lazy
import Data.Attoparsec.Combinator
import Data.Text hiding (foldr)
import qualified Data.Text.Lazy as L (Text, pack)
-- * should succed
t1 = L.pack "hello\t999\nworld\t\900"
t2 = L.pack "world\t\900\nhello\t999\n"
-- * should fail
t3 = L.pack "world\t\900\nhello world\t999\n"
t4 = L.pack "hello world\t999\nworld\t\900"
t5 = L.pack "world hello\t999\nworld\t\900"
p = occur "hello"
---- * discard all text until word `w` occurs, and find its only field `n`
occur :: String -> Parser (String, Int)
occur w = do
pUntil w
string . pack $ w
string "\t"
n <- natural
string "\n"
return (w, read n)
-- * Parse a natural number
natural :: Parser String
natural = many1' digit
-- * skip over all words in Text stream until the word we want
pUntil :: String -> Parser String
pUntil = manyTill anyChar . lookAhead . string . pack