1

I am currently trying to extract the following decimal number:

2453.6756667756

from the following sentence:

ID: 1 x: 1202 y: 2453.6756667756 w: 242

I am using this code:

regularExpression.setPattern("(\\d+)(?:\\s*)(w:)")

However it gives me this result:

6756667756

which is not correct at all.

Could you help me please ?

Dave_Dev
  • 193
  • 12

1 Answers1

4

You can use the following regex:

\d+\.\d+(?=\s*w:)

See demo

In Qt:

regularExpression.setPattern("\\d+\\.\\d+(?=\\s*w:)")

The regex matches:

  • \d+ - 1 or more digits
  • \. - a literal dot
  • \d+ - 1 or more digits
  • (?=\s*w:) - a positive lookahead making sure there is zero or more whitespace symbols after the last digit matched and a w followed by : (but this substring is not consumed, just checked for presence since lookaheads are zero-width assertions).

You can use a simpler regex without a lookahead with a capturing group:

(\d+\.\d+)\s*w:

Then, the value will be in Group 1.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • 1
    Hi, thank you for your help ! I did not know that this excellent website existed. It's going to be very useful ! – Dave_Dev Dec 28 '15 at 23:12
  • 1
    Just note that regex101.com does not support Qt regex syntax. To make sure these will work in Qt, do not use lazy quantifiers (`??`, `*?`, `+?`, `{1,5}?`) and make sure you use `/s` modifier to force `.` to match newlines as in Qt a `.` matches a newline. Well, for basic patterns like this one, it should do. – Wiktor Stribiżew Dec 28 '15 at 23:14
  • One last question. Do you recommend me a particular tutorial which talks about regular expressions ? How to be as good as you are in regular expressions ? It is something very useful in developing. – Dave_Dev Dec 28 '15 at 23:15
  • 2
    Here is my usual answer to this question: I do not know your level of regex knowledge :) so that I can only suggest doing all lessons at [regexone.com](http://regexone.com/), reading through [regular-expressions.info](http://www.regular-expressions.info), [regex SO tag description](http://stackoverflow.com/tags/regex/info) (with many other links to great online resources), and the community SO post called [What does the regex mean](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean). And the most efficient is to answer regex questions here on SO. :) – Wiktor Stribiżew Dec 28 '15 at 23:18
  • Well, I am really a beginner in regular expressions. However, I think that all your advice are going to help me a lot. Thank you so much ! :) – Dave_Dev Dec 28 '15 at 23:21