How to extract a floating number from a string but excluding other number in the same string

Viewed 93

I have the following string:

"You have selected: 7 Year Fixed Price 8.25¢/item"

How do I extract only "8.25" from this string in C#?

I have tried the following regex options: (\d+)(?:\.(\d{1,2}))? and -?\d+(?:\.\d+)? but both extract only "7", which is the first number it finds.

2 Answers

Use

\d+(?:\.\d+)?(?=\p{Sc}/item)

See proof.

Explanation

--------------------------------------------------------------------------------
  \d+                      digits (0-9) (1 or more times (matching
                           the most amount possible))
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    \.                       '.'
--------------------------------------------------------------------------------
    \d+                      digits (0-9) (1 or more times (matching
                             the most amount possible))
--------------------------------------------------------------------------------
  )?                       end of grouping
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    \p{Sc}                 a currency sign
--------------------------------------------------------------------------------
    /item                  '/item'
--------------------------------------------------------------------------------
  )                        end of look-ahead
Related