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

arc*_*oon 25 regex haskell

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

ghci > :m Text.Regex.Posix
ghci > "foo foo foo" =~ "foo" :: [String]
["foo","foo","foo"]
Run Code Online (Sandbox Code Playgroud)

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

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]
Run Code Online (Sandbox Code Playgroud)

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

ham*_*mar 28

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

Prelude> :m + Text.Regex.Posix
Prelude Text.Regex.Posix> getAllTextMatches $ "foo foo foo" =~ "foo" :: [String]
["foo","foo","foo"]
Run Code Online (Sandbox Code Playgroud)

  • 自RWH问世以来,正则表达式接口已更新. (9认同)
  • 好吧,那行得通。谢谢。您知道为什么在教程中似乎没有提到它吗? (2认同)