Python regex for integer?
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
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 string
Note: 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.