Regex to find if a string contains all numbers 0-9 be it in any order. Can anyone help?
Suppose I have a string- "01230912747238507156" This has all characters from 0-9. So I should get True.
Regex to find if a string contains all numbers 0-9 be it in any order. Can anyone help?
Suppose I have a string- "01230912747238507156" This has all characters from 0-9. So I should get True.
You could use a counter like this
string = "01230912747235071568"
cnt = 0
for i in range(0,10):
if str(i) in string:
print(i)
cnt += 1
print(cnt)
If you are really looking for a regex solution (learning purposes?), you could use multiple lookaheads (not advisable, really redundant code):
import re
rx = re.compile(r'^(?=^0*0)(?=^1*1)(?=^2*2)(and so on...).+$')
That is:
(?=not_one zero or more times, then one)...
This solution can handle all sorts of strings, not only numeric characters.
s1 = 'ABC0123091274723507156XYZ' # without 8
s2 = 'ABC0123091274723507156XYZ8'
len(set("".join(re.findall(r'([\d])', s1)))) == 10 # False
len(set("".join(re.findall(r'([\d])', s2)))) == 10 # True
How it works:
Find all digits in the string with regex findall
. Join all matches to one string and get unique characters by putting it in a set
. Then count the length of the set
. If all digits are represented the length will be 10.
You could just use .isdigit()
to filter for non numbers it returns a boolean.
This has the limitation of only working for contiguous numbers/integers.