Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Qt, what takes the least amount of code to replace string matches with regular expression captures?

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.

like image 484
Anon Avatar asked Nov 12 '15 10:11

Anon


People also ask

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group. For more information about numbered capturing groups, see Grouping Constructs.

Is regex faster than string replace Python?

The regexes would probably be faster. A good regex engine (and Python has a good one) is a very fast way to do the sorts of string transformations it can handle. Unless you're really good with regexes though, it will be a bit harder to understand.


1 Answers

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.

like image 166
HeyYO Avatar answered Sep 26 '22 14:09

HeyYO