使用
matchAll
的关键是在创建正则表达式时使用类型注释
:: Regex
:
import Text.Regex
import Text.Regex.Base
re = makeRegex "[^aeiou]" :: Regex
test = matchAll re "the quick brown fox"
这会返回一个数组列表。如果要得到一个(偏移量,长度)对的列表,只需访问每个数组的第一个元素:
import Data.Array ((!))
matches = map (!0) $ matchAll re "the quick brown fox"
要使用=~
运算符,自RWH以来可能发生了变化。您应该使用预定义类型MatchOffset
和MatchLength
以及特殊类型构造函数AllMatches
:
import Text.Regex.Posix
re = "[^aeiou]"
text = "the quick brown fox"
test1 = text =~ re :: Bool
test2 = text =~ re :: String
test3 = text =~ re :: (MatchOffset,MatchLength)
test4 = text =~ re :: AllMatches [] (MatchOffset, MatchLength)
test4' = getAllMatches $ (text =~ re :: AllMatches [] (MatchOffset, MatchLength))
请查看
Text.Regex.Base.Context文档以了解更多可用上下文的详细信息。
更新:我相信类型构造函数
AllMatches
是为了解决正则表达式具有子表达式时引入的歧义而引入的,例如:
foo = "axx ayy" =~ "a(.)([^a])"
test1 = getAllMatches $ (foo :: AllMatches [] (MatchOffset, MatchLength))
test2 = foo :: MatchArray
两者都是偏移-长度对的列表,但它们所代表的含义不同。