gpt4 book ai didi

python - 从字符串中提取2组数字

转载 作者:行者123 更新时间:2023-12-01 03:06:05 25 4
gpt4 key购买 nike

我有一个棘手的 python reg ex 问题,我无法解决:

'alabama_bal_188321000_2000_name_variable_nmr_sw.csv'

我需要处理像上面这样的字符串,并分别提取 2 个数字:1883210002000。 9 位数字之前可能有 0 个或多个下划线(在本例中为 188321000)。此外,2000 之后的文本长度是可变的。

本质上我想提取该字符串中的 2 组数字。

最佳答案

你可以试试这个,

代码:

import re

regex = r"-?\d+"

test_str = "'alabama_bal_188321000_2000_name_variable_nmr_sw.csv'"

matches = re.finditer(regex, test_str)

for matchNum, match in enumerate(matches):
matchNum = matchNum + 1

print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1

print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

结果:

Match 1 was found at 13-22: 188321000
Match 2 was found at 23-27: 2000

关于python - 从字符串中提取2组数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43405423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com