繁体   English   中英

Python 3.7:在开头具有空格的字符串上使用正则表达式

[英]Python 3.7: Using regex on a string with whitespace in the beginning

我在文本文件中有一些行,需要用正则表达式进行解析并将数字分配给变量。 这是线条的示例

      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分配给变量?

您可以使用以下正则表达式。

^\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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM