我最近开始研究 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();
}
我已经搜索了返回子字符串的函数,但直到现在我还没有找到它。 left()、right()、mid()
等函数执行一些类似的任务,但并不完全相同。所以请任何人告诉我我该怎么做。
最佳答案
我想您正在寻找 QRegExp::capturedTexts()
。
来自 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")
关于c++ - 如何使用 QRegExp 从 QString 中获取子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30474594/