首页 > 编程技术 > python

一篇文章带你入门Python正则表达式

发布时间:2021-10-19 16:00

Python3 正则表达式

正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。本文主要阐述re包中的主要函数。

在阐述re包中的函数之前,我们首先看议案正则表达式的模式,即使用特殊的语法来表示一个正则表达式。

Image Name

Image Name

1.match函数

匹配对象方法:

import re
print(re.match("xixi", "xixi_haha_heihei").group())

xixi

line = 'Cats are smarter than dogs'
b = re.match(r'(.*) are (.*?) .*', line, re.M|re.I)

print(b.group()) # 返回所有
print(b.group(1)) # 返回第一组,即(.*)对应的
print(b.group(2)) # 返回第二组,即(.*?)对应的

Cats are smarter than dogs
Cats
smarter

2.search函数

re.search 扫描整个字符串并返回第一个成功的匹配。

函数用法:re.search(pattern, string, flags=0)

print(re.match('heihei', 'xixi_haha_heihei'))
print(re.search('heihei', 'xixi_haha_heihei').group())

None
heihei

line = 'Cats are smarter than dogs'
b = re.search(r'(.*) are (.*?) .*', line, re.M|re.I)

print(b.group()) # 返回所有
print(b.group(1)) # 返回第一组,即(.*)对应的
print(b.group(2)) # 返回第二组,即(.*?)对应的

Cats are smarter than dogs
Cats
smarter

search和match的区别

match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而search匹配整个字符串,直到找到一个匹配。

3. sub函数

re提供了re.sub来替换字符串中的匹配项。
函数用法:re.sub(pattern, repl, string, count=0, flags=0)

phone = '133-3333-3333  # this is a phone number'

num = re.sub(r'#.*$', '', phone)
print('phone num', num)
# 移除注释,找到以#开头的。

num = re.sub(r'\D', '', phone)
print('phone num', num)
# 移除非数字内容

phone num 133-3333-3333  
phone num 13333333333

repl是函数的情况

def double(matched):
    value = int(matched.group('value'))
    return str(value * 2)

s = 'A233Sfd34'
print(re.sub('(?P<value>\d+)', double, s))

A466Sfd68

4.compile函数

compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。
函数使用:re.compile(pattern, flags)

pattern = re.compile(r'/d+')
m = pattern.match('ones123412')
print(m)

None

5.findall

在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。
注意:match和search是匹配一次,但是findall是匹配所有。

函数使用:findall(string, pos, endpos)

pattern = re.compile(r'\d+')
result1 = pattern.findall('xixixix 123 heihiehei 456')
result2 = pattern.findall('xixixix 123 heihiehei 456', 0, 15)

print(result1)
print(result2)

['123', '456']
['123']

6.finditer

和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。

ittt = re.finditer(r'\d+', '12dsfasdf123asdf534')
for ttt in ittt:
    print(ttt.group())

12
123
534

7.split

split 方法按照能够匹配的子串将字符串分割后返回列表。

函数使用:

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

print(re.split('\W+', 'xxixix, xixixi, hehiehei'))
print(re.split('(\W+)', ' xxixix, xixixi, hehiehei'))

['xxixix', 'xixixi', 'hehiehei']
['', ' ', 'xxixix', ', ', 'xixixi', ', ', 'hehiehei']

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注猪先飞的更多内容!

标签:[!--infotagslink--]

您可能感兴趣的文章: