Shakti Kumar
Shakti Kumar

Reputation: 137

Regex to allow only negative number in decimals and 0

Need a regular expression that allows 0 and negative numbers only. Below expression is allowing positive numbers also.

^-?[0-9]\d*(\.\d+)?$

Upvotes: 0

Views: 273

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521249

I would use an alternation here:

^(?:0(?:\.0+)?|-\d+(?:\.\d+)?)$

Demo

^(?:                from the start of the input
    0(?:\.0+)?      match 0, or 0.0, 0.00 etc.
    |               OR
    -\d+(?:\.\d+)?  match a negative number, with optional decimal component
)$                  end of the input

Upvotes: 2

Cary Swoveland
Cary Swoveland

Reputation: 110675

I suggest you match with the regular expression

r'^(?:0|-(?:0\.\d+|[1-9]\d*(?:\.\d+)?))$'

Start your engine!

This matches: '0', '-0.123, '-0.000, '0.123, '-17, '-29.33 and '-29.00'

It does not match: '00', '-017', '12' and '44.7'.

Python's regex engine performs the following operations.

^                : match beginning of string
(?:              : begin non-capture group
  0              : match '0'
  |              : or
  -              : match '-'
    (?:          : begin a non-capture group
      0\.\d+     : match '0.' then 
      |          : or
      [1-9]\d*   : match a digit other than zero then 0+ digits
      (?:\.\d+)  : match '.' then 1+ digits in a non-capture group
      ?          : make the non-capture group optional
    )            : end non-capture group
)                : end non-capture group
$                : match end of string

Upvotes: 1

Related Questions