简体   繁体   English

用匹配本身的任意 function 替换正则表达式匹配

[英]Replace regex match by arbitrary function of match itself

I'm trying to write a function of type Text -> (Text -> Text) -> Text that replaces occurrences of a regular expression in a piece of text by something else that is a function of what the regular expression has matched.我正在尝试编写一个 function 类型的Text -> (Text -> Text) -> Text将一段文本中出现的正则表达式替换为正则表达式匹配的 function 的其他内容。 There is subRegex from Text.Regex but this only allows replacing a match with some fixed replacement string whereas I would like the replacement to an an arbitrary function of the match. Text.RegexsubRegex但这仅允许用一些固定的替换字符串替换匹配项,而我希望替换为匹配项的任意 function。 Is there a package that already implements something like that?是否有已经实现类似功能的 package ?

You can use matchRegexAll您可以使用matchRegexAll

matchRegexAll
   :: Regex     -- ^ The regular expression
   -> String    -- ^ The string to match against
   -> Maybe ( String, String, String, [String] )
                -- ^ Returns: 'Nothing' if the match failed, or:
                --
                -- >  Just ( everything before match,
                -- >         portion matched,
                -- >         everything after the match,
                -- >         subexpression matches )

For example:例如:

subFirst :: Regex -> String -> (String -> String) -> String
subFirst rx input f = case matchRegexAll rx input of
    Nothing -> input
    Just (pre, match, post, _) -> pre <> f match <> post

If you want to do this for all matches rather than just the first, you can call this function recursively on the remainder post (left as an exercise).如果您想对所有匹配项而不是第一个匹配项执行此操作,您可以在剩余post中递归调用此 function(作为练习留下)。

For a different approach, it looks like the text-regex-replace replace package might be of use to you.对于另一种方法,看起来text-regex-replace replace package 可能对您有用。 It works directly on Text rather than String , and it appears to have the capability of arbitrary replacement functions (however the usage seems a bit obtuse).它直接作用于Text而不是String ,并且它似乎具有任意替换函数的能力(但是用法似乎有点迟钝)。

If you're willing to write your pattern matching function as a parser instead of a regular expression, then the function Replace.Megaparsec.streamEdit with the match combinator has the signature you're looking for.如果您愿意将与 function 匹配的模式编写为解析器而不是正则表达式,那么带有match组合器的 function Replace.Megaparsec.streamEdit具有您正在寻找的签名。

Here's a usage example in the README是 README 中的一个使用示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM