Search code examples
c++qt

How to get substring from a QString using QRegExp?


I have recently started to work on QT. I have some operations to do with QString. I need to get the sub string of the main string using regex matching the file path in the string.

i want something like following :

QString str=" My file is strored on C:\My Folder\Files\Test.txt , and i need to move it."

QRegExp rx("([a-zA-Z]:\\(?:[^\\:]+\\)*((?:[^:\\]+)\.\w+))"); //matches file path

if(str.contains(rx))
{
      Qstring path=str.substring(rx);
      QMessageBox msgBox;
      msgBox.setText(path); // where path is "C:\My Folder\Files\Test.txt" .
      msgBox.exec();
}

I have searched for the function which returns the sub string , but till now i haven't found it. Some functions like left(), right(), mid() are does some alike task but not exact. So please can anyone tell me how can i do this it.


Solution

  • I suppose you are looking for QRegExp::capturedTexts(). An example from the official documantation:

    QRegExp rx("(\\d+)(\\s*)(cm|inch(es)?)");
    int pos = rx.indexIn("Length: 36 inches");
    QStringList list = rx.capturedTexts();
    // list is now ("36 inches", "36", " ", "inches", "es")