是否有一个高级API用于在Haskell中使用正则表达式进行搜索和替换?特别是,我正在看Text.Regex.TDFA或Text.Regex.Posix包.我真的很喜欢某种类型:
f :: Regex -> (ResultInfo -> m String) -> String -> m String
Run Code Online (Sandbox Code Playgroud)
所以,例如,用"cat"代替"dog"你可以写
runIdentity . f "dog" (return . const "cat") -- :: String -> String
Run Code Online (Sandbox Code Playgroud)
或者使用monad做更高级的事情,比如计算事件等.
Haskell的文档非常缺乏.一些低级别的API说明是这里.
Sim*_*mon 28
如何subRegex在包中Text.Regex?
Prelude Text.Regex> :t subRegex
subRegex :: Regex -> String -> String -> String
Prelude Text.Regex> subRegex (mkRegex "foo") "foobar" "123"
"123bar"
Run Code Online (Sandbox Code Playgroud)
我不知道任何创建此功能的现有功能,但我认为我最终会使用像模拟它的AllMatches [] (MatchOffset, MatchLength)实例RegexContent:
replaceAll :: RegexLike r String => r -> (String -> String) -> String -> String
replaceAll re f s = start end
where (_, end, start) = foldl' go (0, s, id) $ getAllMatches $ match re s
go (ind,read,write) (off,len) =
let (skip, start) = splitAt (off - ind) read
(matched, remaining) = splitAt len matched
in (off + len, remaining, write . (skip++) . (f matched ++))
replaceAllM :: (Monad m, RegexLike r String) => r -> (String -> m String) -> String -> m String
replaceAllM re f s = do
let go (ind,read,write) (off,len) = do
let (skip, start) = splitAt (off - ind) read
let (matched, remaining) = splitAt len matched
replacement <- f matched
return (off + len, remaining, write . (skip++) . (replacement++))
(_, end, start) <- foldM go (0, s, return) $ getAllMatches $ match re s
start end
Run Code Online (Sandbox Code Playgroud)