Python regular expression to match an integer as string

Is there really a need for Regex here? You have str.isdigit:

>>> string_list = ['123', 'a', '467','a2_2','322','21']
>>> [x for x in string_list if x.isdigit()]
['123', '467', '322', '21']
>>>

The problem is that your pattern contains the *, quantifier, will match zero or more digits. So even if the string doesn't contain a digit at all, it will match the pattern. Furthermore, your pattern will match digits wherever they occur in the input string, meaning, a2 is still a valid match because it contains a digit.

Try using this pattern

^[0-9]+$

Or more simply:

^\d+$

This will match one or more digits. The start (^) and end ($) anchors ensure that no other characters will be allowed within the string.

Tags:

Python

Regex