[Interest] QRegularExpression for replace

Scott Bloom scott at towel42.com
Mon Dec 5 18:28:14 CET 2022


I have implemented the following replacement patterns in a stand-alone function 

It supports numbered groups, named groups, $$, and $&.  My next step is $` $' $+ and $_

Here is how its used in my code base (from my unit tests)


        auto pattern = R"(\p{Sc}*\s?(\d+[.,]?\d*)\p{Sc}*)";
        auto replacement = "$1";
        auto input = R"($16.32 12.19 £16.29 €18.29  €18,29)";
        auto result = NSABUtils::NStringUtils::regExReplace( input, pattern, replacement ); 

        auto pattern = R"(\p{Sc}*\s?(?<amount>\d+[.,]?\d*)\p{Sc}*)";
        auto replacement = "${amount}";
        auto input = R"($16.32 12.19 £16.29 €18.29  €18,29)";
        auto result = NSABUtils::NStringUtils::regExReplace( input, pattern, replacement );

        auto pattern = R"(\p{Sc}*\s?(?<amount>\d+[.,]?\d*)\p{Sc}*)";
        auto replacement = "$ $${amount}";
        auto input = R"($16.32 12.19 £16.29 €18.29  €18,29)";
        auto result = NSABUtils::NStringUtils::regExReplace( input, pattern, replacement );

        auto pattern = QString( R"(\b(\d+)(%1(\d+))?)" ).arg( cSeparator );
        auto replacement = "$ " + QString( "$1$2" );
        EXPECT_EQ( "$ 16.35", NSABUtils::NStringUtils::regExReplace( "16.35", pattern, replacement ) );


I would prefer if it was something like
       Result = regex.replace( replacePattern )

Here is the notes for C#'s regular expression replacement.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/substitutions-in-regular-expressions?redirectedfrom=MSDN#substituting-a-numbered-group

Yes, it can be done, but I think it should be built into QRegularExpression

-----Original Message-----
From: Elvis Stansvik <elvstone at gmail.com> 
Sent: Monday, December 5, 2022 5:37 AM
To: Scott Bloom <scott at towel42.com>
Cc: Thiago Macieira <thiago.macieira at intel.com>; interest at qt-project.org
Subject: Re: [Interest] QRegularExpression for replace

Maybe I'm dumb, but I'm still not sure what is being asked for.

If it's regular expression replacement with back-references in the replacement string, I think that's possible with QString::replace like I showed.


More information about the Interest mailing list