I'm pretty new to Python and I just started learning regex. I'm trying to define a function that takes as input a string containing zero or more sequences of digits and returns a list of all sequences of digits in the string and sorts them. If there isn't it will print that there isn't any.
Here's my code:
def DigitSequence(string):
pattern=re.compile(r'[0-9]+')
k=re.findall(pattern,string)
if len(k)!=0:
return(sorted(k))
else:
return('None')
print( DigitSequence("My number is 98765 and my friend\'s number is 12345.") )
#This should return me ['12345','98765']. And it does.
But is there any better way to do it. Are there any cases I would miss if I do this. I thought of using pattern=re.compile(r'\d*') but I felt it was equivalent to what I did. Correct me if I am wrong.
\dis exactly the same as[0-9], however the quantifiers you used in those patterns are different.*matches the preceding entity zero or more times, while+matches one or more times. So yeah, in many cases those two patterns will give you the same result, but there's an important distinction.