Tag Archives: cpp

Use QRegExp Carefully

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.

Example Case

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 +:

  • str
    /home/dahiya/test+examples/newFile
  • QRegExp(str)
    /home/dahiya/testexamples/newFile
    /home/dahiya/testtexamples/newFile
    /home/dahiya/testttexamples/newFile
    /home/dahiya/testtttexamples/newFile
    /home/dahiya/testttttexamples/newFile

It will never match the original string (str). The index returned will be not be the valid one.

Solution

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).

  • str
    /home/dahiya/test+examples/newFile
  • escape(str)
    /home/dahiya/test\\+examples/newFile

So one can write the correct code like:

int index = list.indexOf(QRegExp(QRegExp::escape(str)));

Conclusion

In future, use QRegExp carefully if you just want to match a string.