[Interest] QRegularExpression for replace

Elvis Stansvik elvstone at gmail.com
Sun Dec 4 20:21:19 CET 2022


Den tors 1 dec. 2022 kl 20:44 skrev Scott Bloom <scott at towel42.com>:
>
> Im looking for a way using QRE to do something like the following
>
>
>
> auto regEx = QRegularExpression( “(?<name>.*)” );
>
> if ( regEx.match( string ) )
>
>                 auto newString = regEx.replace( string, “${name}” );

It's a bit hard to know exactly what you want given the example above,
since the .* would match the entire input string.

But like Tony said, you can make references to the capturing groups in
the replacement string, so e.g.

#include <QString>
#include <QRegularExpression>
#include <QtDebug>

int main(void) {
   QString s = "Hello Jane and Joe";
   qDebug() << s.replace(QRegularExpression("(Jane|Joe)"), "little \\1");
   return 0;
}

will print

"Hello little Jane and little Joe"

I don't think you can reference capturing groups by name, but that's
just a minor inconvenience.

Elvis

>
>
>
>
>
> Using the standard set of regex subsitutions
>
>
>
> Is this something anyone is looking at? Or is there a solution outthere?
>
> Scott
>
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> https://lists.qt-project.org/listinfo/interest


More information about the Interest mailing list