您的位置:首页 > 编程语言 > Python开发

Python 正则表达式 Re模块的一些简单入门知识

2017-12-06 00:00 1016 查看
摘要: 要想抓取一个网页,
首先要会用Python Request,
其次就是Python正则表达式。
就这样默默努力,
总有一天会得到自己想要的,
-------------------------------------------------

Python 正则表达式

检查一个字符串是否与某种模式匹配

re模块提供了Perl风格的正则表达式模式

re模块使Python语言拥有全部的正则表达式功能

re提供与compile()生成的正则表达式对象拥有的一些列方法功能完全一致的函数

1.re.match()

从字符串的起始位置匹配一个模式,如果不是从起始位置匹配,返回None

re.match('匹配的正则表达式', '要匹配的字符串', '标志位,控制正则表达式的匹配方式')

re.match(pattern, string, flags=0)

# -*- coding: utf-8 -*-
import re
# 在起始位置匹配
print re.match('www', 'www.runoob.com').span()      # (0, 3)
# 不在起始位置匹配
print re.match('com', 'www.runoob.com')         # None

2.使用group(num)或者groups()来获取匹配表达式

可以同re.match()/re.search()搭配使用

# -*- coding: utf-8 -*-
import re
line = 'Cats are smarter than dogs'
matchObj = re.match(r'(.*) are (.*?) .*', line, re.M|re.I)      # 大小写不敏感、多行匹配
if matchObj:
print 'matchObj.group(): ', matchObj.group()        # Cats are smarter than dogs
print 'matchObj.group(1): ', matchObj.group(1)      # Cats
print 'matchObj.group(2): ', matchObj.group(2)      # smarter
else:
print 'No match'

3.re.search()

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

re.search('匹配的正则表达式', '要匹配的字符串', '标志位,控制正则表达式的匹配方式')

re.match(pattern, string, flags=0)

# -*- coding: utf-8 -*-
import re
# 在起始位置匹配
print re.search('www', 'www.runoob.com').span()     # (0, 3)
# 不在起始位置匹配
print re.search('com', 'www.runoob.com').span()     # (11, 14)

4.re.match()与re.search()的区别

re.match():只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,直接返回None

re.search():匹配整个字符串,直到找到一个匹配

# -*- coding: utf-8 -*-
import re
line = 'Cats are smarter than dogs'
matchObj = re.match(r'dogs', line, re.M|re.I)
if matchObj:
print 'match: ', matchObj.group()
else:
print 'No match'

searchObj = re.search(r'dogs', line, re.M|re.I)
if matchObj:
print 'search: ',  searchObj.group()
else:
print 'No search'

# 输出
# No match
# No search

5.检索和替换

re.sub('正则中的模式字符串', '替换的字符串/可以是一个函数', '要被查找替换的原始字符串', '模式匹配后替换的最大次数', '标志位')

re.sub(pattern, repl, string, count=0, flags=0) 用于替换字符串中的匹配项

# -*- coding: utf-8 -*-
import re
phone = '2004-959-559 # 这是一个国外电话号码'

# 删除字符串中的Python注释
num = re.sub(r'#.*$', '', phone)
print '电话号码是:', num     # 2004-959-55

# 删除非数字的字符串
num = re.sub(r'\D', '', phone)
print '电话号码是:', num     # 200495955

6.正则表达式修饰符-可选标志

多个标志位可以用|来指定

re.I 对大小写不敏感

re.L 做本地化识别匹配

re.M 多行匹配,影响^和$

re.S 使.匹配包括行在内的所有字符

re.U 根据Unicode字符集解析字符
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: