代码
:
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')