简体   繁体   中英

Extract a decimal number from a sentence using a QRegularExpression

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM