I'm learning regex and I would like to use a regular expression in Python to define only integers - whole numbers but not decimals.
I could make one that only allows numbers by using \d
, 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?
One minor point: \d means any decimal digit, so if you are using Python 3 it will match more than just 0 .. 9 . e.g. re. match("\d", "\u0665") will match (and also int("\u0665") gives 5 ).
1.5 Example: Positive Integer Literals [1-9][0-9]*|0 or [1-9]\d*|0. [1-9] matches any character between 1 to 9; [0-9]* matches zero or more digits. The * is an occurrence indicator representing zero or more occurrences. Together, [1-9][0-9]* matches any numbers without a leading zero.
To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string. [0-9]+ represents continuous digit sequences of any length.
Python Regex Metacharacters[0-9] matches any single decimal digit character—any character between '0' and '9' , inclusive. The full expression [0-9][0-9][0-9] matches any sequence of three decimal digit characters.
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 with a sign could be for example
^[-+]?[0-9]+$
meaning
^
- start of string[-+]?
- an optional (this is what ?
means) minus or plus sign[0-9]+
- one or more digits (the plus means "one or more" and [0-9]
is another way to say \d
)$
- end of stringNote: having the sign considered part of the number is ok only if you need to parse just the number. For more general parsers handling expressions it's better to leave the sign out of the number: source streams like 3-2
could otherwise end up being parsed as a sequence of two integers instead of an integer, an operator and another integer. My experience is that negative numbers are better handled by constant folding of the unary negation operator at an higher level.
You need to anchor the regex at the start and end of the string:
^[0-9]+$
Explanation:
^ # Start of string [0-9]+ # one or more digits 0-9 $ # End of string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With