简体   繁体   中英

Ignoring letters and parsing only numbers using Parsec

This code works only when numerals (eg: "1243\\t343\\n" ) are present:

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 ?

You can skip everything except digits using 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. Otherwise something as easy as

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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