如何使用 QRegExp 从 QString 获取子字符串?

sAc*_*re. 1 c++ qt

我最近开始从事QT的工作。我有一些与 QString 相关的操作。我需要使用与字符串中的文件路径匹配的正则表达式来获取主字符串的子字符串。

我想要类似以下内容:

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();
}
Run Code Online (Sandbox Code Playgroud)

我已经搜索了返回子字符串的函数,但到目前为止我还没有找到它。有些函数(例如left(), right(), mid()are)执行一些相似的任务,但不完全相同。所以请有人告诉我我该怎么做。

han*_*ank 7

我想你正在寻找QRegExp::capturedTexts(). 官方文档中的一个示例:

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")
Run Code Online (Sandbox Code Playgroud)