Ludisposed
Ludisposed

Reputation: 1769

Python regex find nth number

For learning purposes I am doing some regex challenges from CodeFights. Now they have very specific rules in what to change to get the correct result. I solved the puzzle using a different method and I can't wrap my head around how they want me to do it.

Q: return the nth number of a giving string not leaded by zero's

Example

# I can only change ... to solve it
# def nthNumber_asked(s, n):
#    pattern = ...
#    return re.match(pattern, s).group(1)

# How I solved it
def nthNumber_mine(s, n):
    return re.findall(r'(0*)([0-9]+)', s)[n-1][1]

s1 = "8one 003number 201numbers li-000233le number444"
s2 = "LaS003920tP3rEt4t04Yte0023s3t"

print(nthNumber_mine(s1, 4)) # Expected outcome = 233
print(nthNumber_mine(s2, 4)) # Expected outcome = 4

Upvotes: 0

Views: 1122

Answers (2)

JohanL
JohanL

Reputation: 6891

To fullfil the requirements you can use this regex:

def nthNumber_asked(s, n):
    pattern = "\D*(?:\d+\D+){" + str(n-1) + "}0*(\d+)"
    return re.match(pattern, s).group(1)

First I look for a non-digit, then n-1 groups of digits + non-digits (non-capturing) and then finally I ignore all zeros, and catch the rest of the number. However, ignoring all zeros is a bad idea if there is a number that is only zeros, as that will be ignored. I would prefer to include the zeros in the number. Otherwise a more complex pattern with look-ahead is probably needed.

Upvotes: 2

logi-kal
logi-kal

Reputation: 7880

def nthNumber_mine(s, n):
    return re.search(r'(?:\d+.+?){%d}0*(\d+)' % (n-1), s).group(1)

(?:\d+\D+?){%d} matches at least 1 digit followed by at least 0 other chars, for n-1 times. Then at least 0 zeroes are matched, then at least a digit is matched (that is what you are looking for).

Upvotes: 1

Related Questions