如何在python中获取regex中的组

2024-10-02 16:22:24 发布

您现在位置: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新手。你知道吗


Tags: 代码textregroupmatcherxxxprintabcd
1条回答
网友
1楼 · 发布于 2024-10-02 16:22:24

代码

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

因为正则表达式中只有一个组。你知道吗

通过以下方式更改代码,regex解释如下 https://regex101.com/r/BjTrgU/2,您将有一个匹配项(整行)和四个组,您可以分别访问它们来提取数字。你知道吗

区分匹配(当regex匹配/验证输入字符串时)和存储在regex组中的值(每个值由括号()定义)之间的区别是很重要的

正则表达式中第一次出现的()可以通过正则表达式(或替换字符串)或正则表达式外的group(1)中的backreference \1访问,正则表达式中第二次出现的()可以通过正则表达式(或替换字符串)或正则表达式外的group(2)中的backerefence \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')

相关问题 更多 >