I've got a string that may or may not contain a number of 4 or 5 digits. I'm looking for a regex that can detect if the string does in fact have such a number.
To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.
Python Regex – Get List of all Numbers from String. 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.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).
The foolproof one to avoid longer numbers would be:
([^\d]|^)\d{4,5}([^\d]|$)
I'm assuming you don't want to allow for a comma after the thousands digit? If you do then:
([^\d]|^)\d{1,2},\d{3}([^\d]|$)
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