我在Qstring中有文件的整个路径
Qstring str = "d://output/File_012_xyz/logs";
我想从中提取数字12。
我尝试过这样的事情
QRegularExpression rx("[1-9]+");
QRegularExpressionMatchIterator i = rx.globalMatch(str );
if (i.hasNext())
{
QRegularExpressionMatch match = i.next();
QString word = match.captured(1);
quint32 myNum = word.toUInt();
}
这总是将myNum返回为0。在这里我在做什么错?
最佳答案
您要求使用 .captured(1)
返回捕获组#1的值,但您的正则表达式中未定义捕获组。
您可以使用
QRegularExpression rx("[1-9][0-9]*");
QRegularExpressionMatchIterator i = rx.globalMatch(str );
if (i.hasNext())
{
QRegularExpressionMatch match = i.next();
QString word = match.captured(0); // <<< SEE HERE
quint32 myNum = word.toUInt();
}
第
0
组是整个匹配项。另外,像
[1-9]+
这样的模式将不匹配10
或200
,因此,我建议使用[1-9][0-9]*
:一个非0的数字,后跟0或多个数字。
关于c++ - QRegularExpression查找文件名的数字部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61251497/