Fix a regex to exclude false results

Viewed 37

I'm writing a file parser... I have this string

line = "E-Cluster HW active residency:  57.25% (600 MHz:   0% 972 MHz:  32% 1332 MHz: 6.8% 1704 MHz:  11% 2064 MHz:  50%)\n"

line.gsub(/[^\d.]/,'')
=> "57.2560009723213326.8170411206450"

line.match(/:\s+(\d+)/)[1]
=> "57"

I need '57.25'

How can I fix it?

2 Answers

You can try this:

line = "E-Cluster HW active residency:  57.25% (600 MHz:   0% 972 MHz:  32% 1332 MHz: 6.8% 1704 MHz:  11% 2064 MHz:  50%)\n"

line.gsub(/[^\d.]+/,'').match(/\d+\.\d{1,2}/)[0]
=> "57.25"

A match with regex /\d+\.\d{2}/ gets you string up to 1 or 2 decimal points only.

Extract the first number with

line = "E-Cluster HW active residency:  57.25% (600 MHz:   0% 972 MHz:  32% 1332 MHz: 6.8% 1704 MHz:  11% 2064 MHz:  50%)\n"
line[/\d+(?:\.\d+)?/]
=> "57.25"

See Ruby code 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
Related