Dac Saunders Dac Saunders - 1 year ago 75
Python Question

Python regex for integer?

I'm learning reg ex and I would like to use a regular expression in Python to define only integers - whole numbers not decimals. I could make one that only allows numbers by using

, but it also allows decimal numbers which I don't want:

price = TextField(_('Price'),[validators.Regexp('\d', message=_('This is not an integer number, please see the example and try again')),validators.Optional()]

How can I change the code to only allow integers?

Thank you

Answer Source

Regexp work on the character base, and \d means a single digit 0...9 and not a decimal number.

A regular expression that matches only integers could be for example



  1. ^ - start of string
  2. -? - an optional (this is what ? means) minus sign
  3. [0-9]+ - one or more digits (the plus means "one or more" and [0-9] is another way to say \d)
  4. $ - end of string
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download