Re——正则表达式_对象(regex) and (match)

正则表达式对象(regex):

re.complie(pattern, flag=0) return regex对象

/* 因为与上个文章re的方法类似就不多介绍…
1、 regex.search(string[, pos[, endpos]])


2、regex.match(string[, pos[, endpos]])


3、 regex.fullmatch(string[, pos[, endpos]])


4、regex.split(string, maxsplit=0)


5、 regex.findall(string[, pos[, endpos]])


6、regex.finditer(string[, pos[, endpos]])


7、 regex.sub(repl, string, count=0)


8、 regex.subn(repl, string, count=0)


9、 regex.flags
—> 创建对象时的flag参数,一般遵循这样的规则 regex.flags = 32(不加任何flag) + re.*对应的码。


10、 regex.groups
—> regex中pattern的捕获组的数量(就是括号的数量)

eg: >>> r = re.compile('d+')
	>>> r.groups
	0
	>>> r = re.compile('(d+)')
	>>> r.groups
	1

11、regex.groupindex
—> 将(?P)定义的任何符号组名映射到组号的字典。如果模式中没有使用符号组,则字典为空。


12、 regex.pattern
—> 返回RE对象的模式字符串(pattern)


查询返回对象(match):

re.search(pattern,str, flag=0) return match对象
re,match(pattern,str, flag=0) return match对象
regex.search(str, flag=0) return match对象
regex.match(str, flag=0) return match对象

1、match.expand(template)
—> 返回通过对模板字符串模板进行反斜杠替换得到的字符串,就像sub()方法所做的那样。

eg: >>> m.group()
	'Eric Brown'
	>>> m.expand(r'His name is 1 2')
	'His name is Eric Brown'
	>>> m.expand(r'His name is g<1> g<2>')
	'His name is Eric Brown'
	>>> m.expand(r'His name is g<first_name> g<last_name>')
	'His name is Eric Brown'

2、match.group([group1, …])
—> 返回匹配项的一个或多个子组(捕获组所匹配到的子字符串)。默认group(0)和group()为整个匹配。

eg: >>> m=re.match(r'(?P<first_name>w+) (?P<last_name>w+)','Eric Brown')
	>>> m.group()
	'Eric Brown'
	>>> m.group(0)
	'Eric Brown'
	>>> m.group(1,2)
	('Eric', 'Brown')

/* 注: :如果正则表达式使用(?P…)语法,那么groupN参数也可以是根据组名标识组的字符串。

eg: >>> m.group('first_name','last_name')
	('Eric', 'Brown')

3、match.__getitem__(g)

eg: >>> m[1]
	'Eric'
	>>> m[2]
	'Brown'
	>>> m[0]
	'Eric Brown'

4、match.groups(default=None)
—> 返回一个tuple,其中包含匹配的所有子组,从1到模式中的任意多个组。默认参数用于未参与匹配的组;默认为None。

eg: >>> m.groups()
	('Eric', 'Brown')

/* 注: 如果捕获组未能匹配到元素,则返回default

eg: >>> m = re.match(r"(d+).?(d+)?", "24")
	>>> m.groups()
	('24', None)

5、match.groupdict(default=None)
—> 返回一个字典,其中包含匹配的所有命名子组,由子组名作为键。默认参数用于未参与匹配的组;默认为None。

eg: >>> m=re.match(r'(?P<first_name>w+) (?P<last_name>w+)','Eric Brown')
	>>> m.groupdict()
	{'first_name': 'Eric', 'last_name': 'Brown'}

6、match.string
—> 返回字符串,效果跟match.group()相同
/* 注: match.group() —> string 不等于match.groups()—> tuple


————2020年4月12日 XXX

原文地址:https://www.cnblogs.com/free-soul/p/12864081.html