Solved Finding exact match for QString in a QStringList
-
I have stringlist,
[marking_property,property,prop,props]
Here, I want to replace, property with ID,
I expect, the stringlist should be[marking_property,ID,prop,props]
How do I do this using QRegularExpression? -
Hi, have you tried http://doc.qt.io/qt-5/qstringlist.html#replaceInStrings-2 ? It contains a small example and seems to do exactly what you want.
-
QString s = "Some text MyWord some more text MyWordAgain"
s.replace("MyWord","AnotherWord")
Now I want to replace occurrences of 'MyWord' only and 'MyWordAgain' would not be replaced. -
@Vinod-Kuntoji You can use a regular expression with http://doc.qt.io/qt-5/qstring.html#replace-12
-
@jsulm ,
I tried like this,
QFile data(filename); data.open(QIODevice::Text | QIODevice::ReadOnly); QString dataText = data.readAll(); QRegularExpression re(oldTag); QString replacementText(newTag); if(!dataText.contains(re)){ qDebug() << "String Not Found.." << endl; return; } dataText.replace(re, replacementText); QFile newData(filename); if(newData.open(QFile::WriteOnly | QFile::Truncate)) { QTextStream out(&newData); out << dataText; } newData.close();
But it is not replacing the exact string.
-
@Vinod-Kuntoji Well, if you only want to replace whole words then you need something like this as regular expression: "\s+MyWord\s+" you cannot just use MyWord as regular expression and expect it to only replace whole words.
You can use this to test regular expressions: https://regex101.com/ -
@jsulm
The problem with\s+MyWord\s+
is that it requires whitespace on either side, so for example if the complete string is onlyMyWord
it won't match.Most regular expressions syntaxes these days allow
\bMyWord\b
where\b
is a non-eat-character "word-boundary" match. I think Qt is saying it allows Perl-flavor regexps, and that supports\b
(and\B
). -
@JNBarchan It was just an example. The exact expression depends on exact needs.