正则表达式(或和分组)

|——或(OR)符号;
()——用括号分组,就像在 Python 表达式中一样

import re

# 正则表达式中的 OR 符号
print(re.findall(r'Hannes|Hobson|Cole', 'Hobson Lane, Cole Howard, and Hannes Max Hapke'))
print(re.findall(r'H|Hobson|Cole', 'Hobson Lane, Cole Howard, and Hannes Max Hapke'))

# 正则表达式中的分组括号
match1 = re.match(r'(P?<animal_stemm>kitt|dogg)y', "doggy")
print(match1.group())
print(match1.group(0))
print(match1.group(1))
print(match1.groups())
print(match1.groups()[0])
print('=========================================')
match2 = re.match(r'((kitt|dogg)(y))', "doggy")
print(match2.group())
print(match2.group(0))
print(match2.group(1))
print(match2.group(2))
print(match2.group(3))
print(match2.groups())
print(match2.groups()[0])
print(match2.groups()[1])
print(match2.groups()[2])

猜你喜欢

转载自blog.csdn.net/fgg1234567890/article/details/114499517