简体   繁体   English

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

[英]Ignoring letters and parsing only numbers using Parsec

This code works only when numerals (eg: "1243\\t343\\n" ) are present: 仅当存在数字(例如: "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

Is there a way to make it parse "abcd\\tefg\\n1243\\t343\\n" such that it ignores the "abcd\\tefg\\n" part ? 有没有办法让它解析"abcd\\tefg\\n1243\\t343\\n" ,从而忽略"abcd\\tefg\\n"部分?

You can skip everything except digits using skipMany . 您可以使用skipMany跳过除数字以外的所有内容。 Something like the next: 类似于下一个内容:

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

or (depending on what you actually need) 或(取决于您的实际需求)

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

So the trick is to modify integers to simply skip letters. 因此,诀窍是修改整数以简单地跳过字母。

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

This handles 12a34 correctly. 这样12a34正确处理12a34 Otherwise something as easy as 否则,事情就像

 many letter *> (read <$> many digit) <* many letter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM