[英]Extract 2 sets of numbers from string
I have a tricky python reg ex question I am not able to solve: 我有一个棘手的python reg ex问题,我无法解决:
'alabama_bal_188321000_2000_name_variable_nmr_sw.csv'
I need to process strings like the one above and extract the 2 numbers separately: 188321000
and 2000
. 我需要处理上述字符串,并分别提取2个数字: 188321000
和2000
。 It is possible that there are 0 or more underscores before the 9 digit number ( 188321000
in this case). 9位数字前可能有0个或多个下划线(在这种情况下为188321000
)。 Also, the length of text after 2000
is variable. 此外, 2000
之后的文本长度是可变的。
Essentially I want to extract the 2 set of numbers in that string. 本质上,我想提取该字符串中的2组数字。
import re
m = re.search('(\d+)_(\d+)', your_string)
print(m.group(1), m.group(2))
This outputs: 输出:
188321000 2000
You can try this, 你可以试试看
Code: 码:
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)))
Results: 结果:
Match 1 was found at 13-22: 188321000
Match 2 was found at 23-27: 2000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.