Lately, I found a silly mistake which I have repeated at a couple of places in my Qt code. I thought of noting it down.
I have a QStringList (list) and I want to find the index of a string (str) in it.
// list - QStringList // str - QString int index = list.indexOf(QRegExp(str)); // this function accepts QRegExp only, though // in the new releases of Qt an overload // accepting QString is also available
Nothing wrong with this, it has been working great for me and I have used it at many places. But, this works as long as str doesn’t contain any RegExp special characters. If the str contains special characters, its meaning changes. For instance dealing with filePaths, filepaths may have special characters in it like the character +.
The meaning of QRegExp(str) changes if str has the character +:
It will never match the original string (str). The index returned will be not be the valid one.
Escape all the RegExp special characters. On escaping the special characters, they will be treated normal and the code will behave correctly. Qt provides a utility function also.
QString QRegExp::escape(const QString&)
This function returns the escaped string (str).
So one can write the correct code like:
int index = list.indexOf(QRegExp(QRegExp::escape(str)));
In future, use QRegExp carefully if you just want to match a string.