忽略字母并使用Parsec仅解析数字

时间:2013-10-06 20:03:21

标签: parsing haskell parsec

此代码仅在存在数字(例如:"1243\t343\n")时起作用:

tabFile = endBy line eol
line = sepBy cell (many1 tab)
cell = integer
eol = char '\n'

integer = rd <$> many digit
  where rd = read :: String -> Int

有没有办法让它解析"abcd\tefg\n1243\t343\n",忽略"abcd\tefg\n"部分?

2 个答案:

答案 0 :(得分:1)

您可以使用skipMany跳过除数字之外的所有内容。像下一个:

many (skipMany (noneOf ['0'..'9']) >> digit)

或(取决于您实际需要的)

skipMany (noneOf ['0'..'9']) >> many digit

答案 1 :(得分:1)

所以诀窍就是修改整数以简单地跳过字母。

integer :: Parser Int
integer =
  many letter *>
  ((read . concat) <$> many digit `sepBy` many1 letter)
  <* many letter

正确处理12a34。否则就像

一样简单
 many letter *> (read <$> many digit) <* many letter