How to search and replace a substring ?
-
I'm looking for a way to replace any sub-string present in a
QString
object that is included in a hard-coded list of strings which include dozens of entries. Right now I'm passingQString::replace
aQRegularExpression
that covers all matching strings. However, I'm not sure this is an adequate way of doing things.Does anyone know what's the best way to pull this off?
-
Hi @rmam,
I have seen implementations that simply nest calls to
QString::replace(QString, QString)
:QString s = "The quick brown fuchs jumps ueber the lazy hund."; s.replace("fuchs", "fox").replace("ueber", "over").replace("hund", "dog");
However, this involves multiple string allocations so it might be slower than a regular expression based replace. Or it might be faster. The only thing you can do is benchmark with your original data.
Happy New Year!
-
@JonB
Sorry got overlooked the post. My opinion is what ever he is used the code that is right. In terms of replacing the strings.QString s = "The quick brown fuchs jumps ueber the lazy hund."; s.replace("fuchs", "fox").replace("ueber", "over").replace("hund", "dog");
Based on @rmam post he has to replace the search string with another specific string.
-
-
@JonB the replacement would be a slightly altered version of the original keyword. For instance, consider that the regex tries to match instances of keyword "foo" that occur only after "this.foo." then the goal is to replace them with, for example "this <bar>foo</bar>."
-
Hi,
Is it some sort of template replacement ?
-
@rmam
You can't use multiplereplace()
s if there is any chance that the replacement string could be found by a search string.Once you start specifying patterns like you are now, you're better off with regular expressions, and you don't have the potential issue of one replacement causing another. So actually your current solution may be good. You can build up the many strings dynamically before passing them as reg exp if that's better to maintain in code, I don't know if Qt has any limits on length of pattern.
Now, of course once @SGaist has spoken it's worth answering him, as he might have a tailored solution :)