从字符串中提取两组数字

2024-04-28 19:56:04 发布

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

我有一个棘手的问题无法解决:

'alabama_bal_188321000_2000_name_variable_nmr_sw.csv'

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

本质上,我想提取字符串中的2组数字。你知道吗


Tags: csv字符串name文本数字swvariablenmr
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
import re
m = re.search('(\d+)_(\d+)', your_string)
print(m.group(1), m.group(2))

这将输出:

188321000 2000

相关问题 更多 >