-3

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.

Abhisek Roy
  • 562
  • 9
  • 28

4 Answers4

4

You can use Python's built-in all() function

See code in use here

s = "0123091274723507156"
n = [0,1,2,3,4,5,6,7,8,9]
print(all(str(i) in s for i in n))

You could also replace [0,1,2,3,4,5,6,7,8,9] with list(range(0,10))

ctwheels
  • 19,377
  • 6
  • 29
  • 60
1

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)...
Jan
  • 38,539
  • 8
  • 41
  • 69
1

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.

Darkonaut
  • 14,188
  • 6
  • 32
  • 48
0

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.

notacorn
  • 1,793
  • 2
  • 13
  • 33
Mike Tung
  • 4,242
  • 1
  • 12
  • 20