如何在Python中使用正则表达式获取分组

54 浏览
0 Comments

如何在Python中使用正则表达式获取分组

这个问题已经有答案了:

如何在Python中查找正则表达式的所有匹配项?

我想在表达式中打印第一、第二和第三个匹配组。以下是细节。

Regex Pattern = "(\d+)"
Expression = "1123-xxx-abcd-45-tsvt-35-pwrst-99-xql"

我使用了Pythex,https://pythex.org/?regex=(%5Cd%2B)&test_string=1123-xxx-abcd-45-tsvt-35-pwrst-99-xql&ignorecase=0&multiline=0&dotall=0&verbose=0它完美地工作,显示了所有捕获的组。

但是在Python代码中没有用。我提供以下Python代码,我无法找到问题所在。

import re
class Test3:
    def printAllGroups(self):
        regexPattern = r"(\d+)"
        text = "1123-xxx-abcd-45-tsvt-35-pwrst-99-xql"
        matcher = re.compile(regexPattern, flags=re.IGNORECASE)
        matchValue = matcher.match(text);
        if matchValue:
            print("First group : ", matchValue.group(1))
            print("Second group : ", matchValue.group(2))
            print("Third group : ", matchValue.group(2))
if __name__ == '__main__':
    test3 = Test3()
    test3.printAllGroups()

请帮助我解决这个问题,我是Python的新手。

admin 更改状态以发布 2023年5月22日
0
0 Comments

代码:

import re
regexPattern = r"(\d+)"
expression = "1123-xxx-abcd-45-tsvt-35-pwrst-99-xql"
print(re.findall(regexPattern,expression))

输出:

['1123', '45', '35', '99']

在你的当前代码中,你会遇到错误:

    print("Second group : ", matchValue.group(2))
IndexError: no such group

因为正则表达式中只有一个组

通过以下方式更改你的代码,使用在https://regex101.com/r/BjTrgU/2解释的正则表达式,你会有一个单一的匹配(整个行),和四个组,你可以单独访问,以提取数字。

区分匹配(当你的正则表达式匹配/验证输入字符串时)和存储在正则表达式的每个组中(由括号()定义)的值非常重要

正则表达式中第一个出现的()将通过正则表达式中的反向引用\1(或替换字符串)或在正则表达式之外的group(1)中进行访问,正则表达式中第二个出现的()将通过反向引用\2(或替换字符串)或外部的group(2)进行访问,...

import re
class Test3:
    def printAllGroups(self):
        regexPattern = r"^(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]+$"
        text = "1123-xxx-abcd-45-tsvt-35-pwrst-99-xql"
        matcher = re.compile(regexPattern, flags=re.IGNORECASE)
        matchValue = matcher.match(text);
        if matchValue:
            print("First group : ", matchValue.group(1))
            print("Second group : ", matchValue.group(2))
            print("Third group : ", matchValue.group(3))
            print("Third group : ", matchValue.group(4))
if __name__ == '__main__':
    test3 = Test3()
    test3.printAllGroups()

输出:

python test3.py
('First group : ', '1123')
('Second group : ', '45')
('Third group : ', '35')
('Third group : ', '99')

0