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

3
  • 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 Commented Sep 20, 2018 at 16:45
  • @Rafael qregexp. That never works. Commented Sep 20, 2018 at 16:46
  • 1
    @revo yeah, that's why it's not an answer :) just a comment Commented Sep 20, 2018 at 16:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.