我在文本文件中有一些行,需要用正则表达式进行解析并为变量分配数字。这是这些行的示例
1 35 A K 0 0 182
因此字符串的开头有空格,并且每当我使用此网站(https://pythex.org/)时,使用正则表达式
似乎都不匹配任何内容。^s+\d+\s+\d+\s\w\s\w\s+\d\s+\d\s+\d
如何使用正则表达式将182分配给变量?
答案 0 :(得分:0)
您可以使用以下正则表达式。
^\s+\d+\s+\d+\s+\w+\s+\w+\s+\d+\s+\d+\s+(\d+)
您可以将最后一个数字放在可以在代码中捕获的组中。
以下是一个测试python脚本。
import re
regex = r"^\s+\d+\s+\d+\s+\w+\s+\w+\s+\d+\s+\d+\s+(\d+)"
test_str = " 1 35 A K 0 0 182"
matches = re.finditer(regex, test_str, re.MULTILINE)
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 0-40: 1 35 A K 0 0 182
Group 1 found at 37-40: 182