finding non zero values in the string using regular expression (regex)

Viewed 125

String 1: _0.05_0.0_0.0_0.0_0.0_0.0_

String 2: _8.5_5.0_0.0_0.0_0.0_1.25_

These are order quantity separated by underscore. How can i count non zero order count using regular expression. Non zero order count in string 1 is 1 (0.05) and in string 2 is 3 (8.5,5.0,1.25).

Tried so far: ^_0.0_$, but it giving wrong result.

Please Help

1 Answers

You can use

(?<=_)(?![0.]+_)\d+\.\d+

See the regex demo.

Details

  • (?<=_) - a _ must occur immediately to the left of the current location
  • (?![0.]+_) - immediately to the right, there cannot be only zeros and .
  • \d+\.\d+ - one or more digits, ., one or more digits.

You can also use

(?<!\d)(?!0+\.0+(?!\d))\d+\.\d+

See this regex demo. Details:

  • (?<!\d) - a left-hand digit boundary
  • (?!0+\.0+(?!\d)) - no one or more zeros, ., one or more zeros not followed with a digit are allowed immediately to the right of the current location
  • \d+\.\d+ - one or more digits, ., one or more digits.
Related