How to regex replace based on match on Qt?

Viewed 34

How i could replace based on match as demonstrated on: https://regex101.com/r/scp8Ar/1

  QString str = "blue red(0) green";
  QRegularExpression re(R"((red)\(0\))");
  str.replace(re, "$01(1)");

str outputs: blue $01(1) green

instead of blue red(1) green

On the regex site, they offer "flavor" of PCRE2 (PHP >= 7.3) and their "Help" for that states "Perl PCRE2"

From the Qt5/Qt6 docs:

QRegularExpression implements Perl-compatible regular expressions.

Would like to understand why I'm getting a different value?

1 Answers

If we follow the example from the documentation:

QString t = "A <i>bon mot</i>.";
t.replace(QRegularExpression("<i>([^<]*)</i>"), "\\emph{\\1}");
// t == "A \\emph{bon mot}."

Then you can use:

QString str = "blue red(0) green";
QRegularExpression re(R"(red)\(0\)");
str.replace(re, "\\1(1)");
// blue red(1) green
Related