I've to split simple QStrings of the form "number number number",for example " 2323 432 1223". The code i use is
QString line;
QRegularExpression re("(\\d+)");
QRegularExpressionMatch match;
while(!qtextstream.atEnd()){
line = qtextstream.readLine();
match = re.match(line);
std::cout<<"1= "<<match.captured(0).toUtf8().constData()<<std::endl;
std::cout<<"2= "<<match.captured(1).toUtf8().constData()<<std::endl;
std::cout<<"3= "<<match.captured(2).toUtf8().constData()<<std::endl;
}
if the first line being processed is like the example string i get for the first while cycle output:
1= 2323
2= 2323
3=
what is wrong?
Your regex only matches 1 or more digits once with
re.match
. The first two values are Group 0 (the whole match) and Group 1 value (the value captured with a capturing group #1). Since there is no second capturing group in your pattern,match.captured(2)
is empty.You must use
QRegularExpressionMatchIterator
to get all matches from the current string:Note that
(\\d+)
contains an unnecessary capturing group, since the whole match can be accessed, too. So, you may usere("\\d+")
and then get the whole match withi.next().captured(0)
.If the usage of regular expressions isn't mandatory, you could also use QString's
split()-function
.