1

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Your main issue is that you only obtained one single match. You need to get *all* matches. Whether there are letters or not, that does not seem to be in scope of this question. Else, please update it. – Wiktor Stribiżew Sep 26 '17 at 10:59
  • If there is an answer that solved your issue please consider accepting/upvoting. If not, please provide a comment describing what is not working/still unclear. – Wiktor Stribiżew Sep 26 '17 at 11:01

2 Answers2

2

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:

QRegularExpressionMatchIterator i = re.globalMatch(line);
while (i.hasNext()) {
    qDebug() << i.next().captured(1); // or i.next().captured(0) to see the whole match
}

Note that (\\d+) contains an unnecessary capturing group, since the whole match can be accessed, too. So, you may use re("\\d+") and then get the whole match with i.next().captured(0).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

If the usage of regular expressions isn't mandatory, you could also use QString's split()-function.

QString str("2323 432 1223");
QStringList list = str.split(" ");
for(int i = 0; i < list.length(); i++){
    qDebug() << list.at(i);
}
JSilver
  • 107
  • 6
  • Yes, but it's irrelevant what the String consists of as long as it is divided by the character/string you use as the parameter of the split-function. – JSilver Sep 27 '17 at 13:15
  • If I've to restrive, for example , 234 3243 4355 from lines like "234e 2143 gt4355",instead with split i get 3 QStrings with the values 234e , 2143 , gt4355,separated but still with letters – Antonio Del Sannio Sep 27 '17 at 13:54