Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement /e modifier with PCRE2?

Tags:

c++

regex

pcre

In Perl, we can do this

s/pattern/func($1)/e

Is there any convenient function that does the same thing with PCRE2, like

::pcre2_substitute_with_callback(
    re, // the compiled pattern
    pcuSubject, ccuSubject, // the subject and its length
    PCRE2_SUBSTITUTE_GLOBAL, // the substitute options
    matches,
    NULL, // the match context
    [](PCRE2_SPTR pcuMatched)->PCRE2_SPTR{ // the callback
        return "replacement";
    },
    pcuResult, &ccuResult
);

Thanks.

like image 857
Cody Avatar asked Sep 11 '26 05:09

Cody


1 Answers

No, I think that there is no such convenience in pcre2. See the wrapper below though.

However, I believe that the replacement string for the call to pcre2_substitute can be prepared without any particular restrictions. (I cannot test now.) The use of escape character ($) for capturing groups or pattern items is clearly specified but I don't see why one couldn't use that in a function/callback to form the replacement string.

That can then be wrapped in a method with a desired signature.

Some more documentation from pcre2api is at Creating a new string with substitutions


There is a C++ wrapper JPCRE2. It uses the replace method of RegexReplace for this purpose. However, about half-way through the main page it also informs us that

There's another replace function (jp::RegexReplace::nreplace()) that takes a MatchEvaluator with a callback function. It's required when you have to create the replacement strings dynamically according to some criteria.

The class jp::MatchEvaluator implements several constructor overloads to take different callback functions.

The page continues with a full example for usage of jp::RegexReplace::nreplace().

More detailed examples are offered in a test file in the distribution.

like image 51
zdim Avatar answered Sep 13 '26 19:09

zdim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!