学习笔记:在Python中使用正则表达式

2018-06-20  本文已影响0人  KayFelicities

主要介绍Python中re库的接口使用。

常用接口

两种用法

pattern = re.compile(r'\d+')
m = pattern.match('12twothree34four')

这种方法一般用于同一个正则表达式匹配多个字符串的情况(正则表达式不用反复编译)。

m = re.match(r'\d+', '12twothree34four')

match(pattern, string, flags=0)

flags:

返回值

match_object
无法匹配时返回None

属性

方法

m = re.match(r'(\w+) (\w+)(?P<sign>[^\w]*)', 'hello world!ab')
m.string  # hello world!ab
m.re  # re.compile('(\\w+) (\\w+)(?P<sign>[^\\w]*)')
m.pos  # 0
m.endpos  # 14
m.lastgroup  # sign
m.group() # 'hello world!'
m.group(1,2)  # ('hello', 'world')
m.groups()  # ('hello', 'world', '!')
m.groupdict()  # {'sign': '!'}
m.start(2)  # 6
m.end(2)  # 11
m.span(2)  # (6, 11)
m.expand(r'\2 \1\3')  # world hello!

search(pattern, string, flags=0)

返回值

match_object
搜索不到时返回None

split(pattern, string, maxsplit=0, flags=0)

与string.split()类似,因为可以使用正则所以更加灵活

maxsplit

指定最大分割次数,不指定将全部分割

返回值

分割后的list

findall(pattern, string, flags=0)

搜索string,以列表形式返回全部能匹配的子串。

返回值

匹配到的字符串的list

finditer(pattern, string, flags=0)

搜索string,以迭代器形式返回全部能匹配的match_object

sub(pattern, repl, string, count=0, flags=0)

使用repl替换string中每一个匹配的子串后返回替换后的字符串
当repl是一个字符串时,可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。
当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。
count用于指定最多替换次数,不指定时全部替换。

返回值

new_string

p = re.compile(r'(\w+) (\w+)')
s = 'i say, hello world!'
 
print(p.sub(r'\2 \1', s))  # say i, world hello!
 
def func(m):
    return m.group(1).title() + ' ' + m.group(2).title()
 
print(p.sub(func, s))  # I Say, Hello World!

subn(pattern, repl, string, count=0, flags=0)

比sub多返回一个替换次数

返回值

(new_string, number_of_subs_made)

参考

https://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html
https://docs.python.org/3/library/re.html

上一篇 下一篇

猜你喜欢

热点阅读