Python regex查找nth numb

2024-09-30 19:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

为了学习的目的,我做了一些来自代码斗争的regex挑战。现在他们有非常具体的规则来改变什么才能得到正确的结果。我用一种不同的方法解决了这个难题,我不知道他们要我怎么做。在

Q:返回不以零开头的给定字符串的第n个数字

示例

# 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

Tags: 代码目的rereturndefitregexpattern
2条回答

要满足要求,可以使用以下正则表达式:

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

首先我寻找一个非数字,然后是n-1组数字+非数字(非捕获),最后我忽略所有的零,然后捕捉剩余的数字。但是,如果有一个只有零的数字,那么忽略所有的零是一个坏主意,因为它将被忽略。我更愿意在数字中加上0。否则,可能需要一个更复杂的具有前瞻性的模式。在

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

(?:\d+\D+?){%d}匹配至少1个数字后跟至少0个其他字符,持续n-1次。然后至少匹配0个零,然后至少匹配一个数字(这就是您要查找的)。在

相关问题 更多 >