Haskell中正则表达式的所有匹配 [英] All matches of regex in Haskell

查看:100
本文介绍了Haskell中正则表达式的所有匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据一些教程(包括真实世界的Haskell),可以使用ghci做以下操作:

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

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

 没有实例(RegexContext Regex [Char] [String])使用'=〜'
引起的
可能的修正:

添加实例声明(RegexContext Regex [Char] [String])
在表达式中:abc=〜ab:: [String]
在'it'的等式中:it =abc=〜ab:: [String]

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


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

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


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?

解决方案

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"]

这篇关于Haskell中正则表达式的所有匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆