7

I was hoping that QString would allow this:

QString myString("School is LameCoolLame and LameRadLame");
myString.replace(QRegularExpression("Lame(.+?)Lame"),"\1");

Leaving

"School is Cool and Rad"

Instead from what I saw in the docs, doing this is a lot more convoluted requiring you to do (from the docs):

QRegularExpression re("\\d\\d \\w+");
QRegularExpressionMatch match = re.match("abc123 def");
if (match.hasMatch()) {
    QString matched = match.captured(0); // matched == "23 def"
    // ...
}

Or in my case something like this:

QString myString("School is LameCoolLame and LameRadLame");
QRegularExpression re("Lame(.+?)Lame");
QRegularExpressionMatch match = re.match(myString);
if (match.hasMatch()) {
    for (int i = 0; i < myString.count(re); i++) {
        QString newString(match.captured(i));
        myString.replace(myString.indexOf(re),re.pattern().size, match.captured(i));
    }
}

And that doesn't even seem to work, (I gave up actually). There must be an easier more convenient way. For the sake of simplicity and code readability, I'd like to know the methods which take the least lines of code to accomplish this.

Thanks.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Anon
  • 2,267
  • 3
  • 34
  • 51

1 Answers1

12
QString myString("School is LameCoolLame and LameRadLame");
myString.replace(QRegularExpression("Lame(.+?)Lame"),"\\1");

Above code works as you expected. In your version, you forgot to escape the escape character itself.

HeyYO
  • 1,989
  • 17
  • 24