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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With