Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All matches of regex in Haskell

Tags:

regex

haskell

According to a number of tutorials (including Real World Haskell) one can, using ghci do the following

ghci > :m Text.Regex.Posix
ghci > "foo foo foo" =~ "foo" :: [String]
["foo","foo","foo"]

Yet, when I attempt this, it yields

No instance for (RegexContext Regex [Char] [String])
  arising from a use of `=~'
Possible fix:
  add an instance declaration for
  (RegexContext Regex [Char] [String])
In the expression: "abc" =~ "ab" :: [String]
In an equation for `it': it = "abc" =~ "ab" :: [String]

What is the correct way of obtaining a list of all matches in haskell?

like image 406
archgoon Avatar asked Jan 28 '12 23:01

archgoon


1 Answers

The regex libraries can be somewhat confusing with their overloaded return types, but to get all the matches you just need to ensure that the return type is AllTextMatches, for example:

Prelude> :m + Text.Regex.Posix
Prelude Text.Regex.Posix> getAllTextMatches $ "foo foo foo" =~ "foo" :: [String]
["foo","foo","foo"]
like image 85
hammar Avatar answered Nov 16 '22 12:11

hammar