Python使用正则表达式的两种方式:
~方式一:不创建正则表达式对象,直接调用函数进行匹配操作
- match
- fullmatch
方式二:创建正则表达式对象(Pattern),通过给对象发消息实现匹配操作
- compile
以下为几个小例子:
1、匹配用户名是否由字母、数字或下划线构成且长度在6~20个字符之间。
使用方法一:
import re
username = input('请输入用户名:')
# matcher = re.fullmatch(r'\w{6,20}',username) 此行代码与下一行等价(\w匹配字母数字下划)
matcher = re.match(r'^\w{6,20}$',username) # 起始符^ 结束符$
if matcher is None:
print('用户名不合法!')
else:
print(matcher.group())
使用方法二:
import re
username = input('请输入用户名')
# 通过comppile编译正则表达式创建Pattern对象
username_pattern = re.compile(r'^\w{6,20}$')
# 通过给Pattern对象发消息实现匹配检查
matcher = username_pattern.match(username)
if matcher is None:
print('无效的用户名!')
else:
print(matcher.group())
2、从字符串中提取跟正则表达式匹配的部分
content = """报警电话:110,我们班是Python-2105班, 我的QQ号是957658,我的手机号是13211223344,谢谢!"""
import re
pattern = re.compile(r'\d+') # \d 匹配数字,+ 匹配1次或多次
matcher = pattern.search(content) # search()从任意位置所搜匹配
while matcher:
# matcher.end() - 下一次搜索从上依次结束位置
matcher = pattern.search(content,matcher.end())
results = pattern.findall(content)
# results = re.findall(r'\d+',content) # 从字符串中找出所有和正则表达式匹配的内容
for result in results:
print(result) # 110 2105 957658 13211223344
3、不良内容过滤
import re
content = '马某某是一个沙雕煞笔,FUck you!'
pattern = re.compile(r'[傻沙煞][逼笔雕鄙]|马某某|fuck|shit', flags=re.IGNORECASE)
# 通过sub --->函数替换
modified_content = pattern.sub('*', content)
print(modified_content) # *是一个**,* you!
4、用正则表达式拆分字符串
import re
poem = '窗前明月光,疑是地上霜。举头望明月,低头思故乡。'
pattern = re.compile(r'[,。]')
sentences_list = pattern.split(poem)
# 去掉拆分后末尾的空字符
sentences_list = [sentence for sentence in sentences_list if sentence]
for sentence in sentences_list:
print(sentence)
16

被折叠的 条评论
为什么被折叠?



