正規表現と一致オブジェクトの属性と属性メソッド

"""
    regex 对象的属性
"""
import re

s = "My name is Kevin,age 25,heigh 45.5"
pattern = '(\d+\.)(?P<float>\d+)'
regex = re.compile(pattern)
print(regex.flags)  # 32 默认值
print(regex.pattern)  # 正则表达式:(\d+\.)(?P<float>\d+)
print(regex.groupindex)  # 捕获组:第几组(从外到内,从左至右数)
print(regex.groups)  # 子组个数:2

上記は正規表現のプロパティです

"""
    match对象的属性和方法
"""
import re

s = "abcdefghi"
pattern = '(ab)cd(?P<pig>efg)'
regex = re.compile(pattern)
match_obj = regex.search(s, 0, 8)
print("===================属性测试===================")
print(match_obj.pos)
print(match_obj.endpos)
print(match_obj.re)  # re.compile('(ab)cd(?P<pig>efg)')
print(match_obj.string)
# 返回最后一个子组的组名,如果最后子组无名,返回None
print(match_obj.lastgroup)  # pig
print(match_obj.lastindex)  # 2 最后一组序列号
print("===================属性方法===================")
# print(dir(match_obj))
print(match_obj.span())  # (0, 7)  匹配内容的位置
print(match_obj.start())
print(match_obj.end())
# match_obj.group():默认为0,表示获取整个match对象内容,如果是序列号或组名表示获取对应子组的内容
print(match_obj.group())  # abcdefg
print(match_obj.groups())  # ('ab', 'efg')  返回子组匹配内容组成的元组
print(match_obj.groupdict())  # 返回一个字典  组名:匹配内容(即捕获组:匹配的内容)
# print(match_obj.expand())

上記はmatchオブジェクトの属性と属性メソッドです。

おすすめ

転載: blog.csdn.net/m0_51489557/article/details/130258279