Haskell中正则表达式的所有匹配

时间:2012-01-28 23:58:14

标签: regex haskell

根据一些教程(包括Real World Haskell),可以使用ghci执行以下操作

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

然而,当我尝试这个时,它会产生

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]

获取haskell中所有匹配列表的正确方法是什么?

1 个答案:

答案 0 :(得分:26)

正则表达式库可能会对它们的重载返回类型造成一些混淆,但要获得所有匹配项,您只需确保返回类型为AllTextMatches,例如:

Prelude> :m + Text.Regex.Posix
Prelude Text.Regex.Posix> getAllTextMatches $ "foo foo foo" =~ "foo" :: [String]
["foo","foo","foo"]