Constantin
Constantin

Reputation: 17798

QRegExp Extract Two Numbers

All I am trying to extract two numbers from a user string. I have the regexp working, but the second number capture is not being greedy enough! I can't figure out how to reformat this to my needs, I am submitting my reg exp any advice would be great!

QRegExp valid_input(".*(-?\\d*\\.?\\d+)[\\s,]+(-?\\d*.?\\d+)[^\d]*");
valid_input.setMinimal(true);

if(valid_input.indexIn(value.toString()) == -1)
    return false;

QPointF new_point(valid_input.cap(1).toDouble(), valid_input.cap(2).toDouble());

Thanks in advance!


Example input: 156, 264

Expected Output: 156 and 264

My Output: 156 and 2


Example input: 156.2 264.52

Expected Output: 156.2 and 264.52

My Output: 156 and 2


Example input: 156.2 264.52)

Expected Output: 156.2 and 264.52

My Output: 156 and 2

Upvotes: 0

Views: 1546

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74078

Two points:

  • AFAICS from the manual you can remove the leading ".*" and trailing "[^\d]*"
  • setMinimal(true) talks about setting the regexp being not greedy.

Otherwise (for lack of example data) your regexp looks fine.

http://www.regular-expressions.info/floatingpoint.html shows

[-+]?[0-9]*\.?[0-9]+

which is basically your regexp, with an additional optional plus sign.

An alternative to that, could be to split the regexp into multiple simpler parts:

([-+]?\.\d+|[-+]?\d+\.\d*|[-+]?\d+)

Upvotes: 2

Vicent
Vicent

Reputation: 5452

Your regex works fine with your examples. Simply do not enable minimal matching and you will get the expected results.

Upvotes: 1

Related Questions