社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中获取regex中的组[duplicate]

Sambit Debadatta Mishra • 5 年前 • 1685 次点击  

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

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新手。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51010
文章 [ 1 ]  |  最新文章 5 年前
Allan
Reply   •   1 楼
Allan    6 年前

代码 :

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 ,您将有一个单独的匹配项(整行)和四个组,您可以单独访问它们来提取数字。

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

第1次出现 () 在regex中可以通过backreference访问 \1 在regex(或替换字符串)中,或者 group(1) 在regex之外,第二次出现 () 在regex中可以通过backerefence访问 \2 在regex(或替换字符串)中,或者 group(2) 在regex之外,。。。

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')