2

I'm quite noob with regular expression, all i want to do is to get all numbers from a string.

QRegExp rx;
rx.setPattern("\\d+");
rx.indexIn("this string contains number 123 and 567*872");
QStringList MyList = rx.capturedTexts();

Expected result is: 123 and 567 and 872. What i get is: 123

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
emazed
  • 23
  • 7
  • Something like this, split the string at nonnumbers, join the array with space, trim string (in javascript): `let s = 'this 123 and 567*872'; s.split(/[^\d]+/).join(' ').trim();//832 832 222` – Rafael Sep 20 '18 at 16:45
  • @Rafael qregexp. That never works. – revo Sep 20 '18 at 16:46
  • 1
    @revo yeah, that's why it's not an answer :) just a *comment* – Rafael Sep 20 '18 at 16:47

1 Answers1

1

You need to get all matches with a loop like

QRegExp rx("\\d+");
QString str = ""this string contains number 123 and 567*872"";
QStringList MyList;
int pos = 0;

while ((pos = rx.indexIn(str, pos)) != -1) {
    MyList << rx.cap(0);
    pos += rx.matchedLength();
}

Here, rx.cap(0) accesses Group 0, the whole match. The QRegExp::indexIn attempts to find a match in str from position offset (0 by default). If offset is -1, the search starts at the last character; if -2, at the next to last character; etc. While the position is not -1, we may iterate through all the matches in the string.

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