Python正则表达式

正则表达式

概述

  正则表达式,又称正规表示式、正规表示法、正规表达式、规则表达式、常规表示法(英语:Regular Expression,在代码中常简写为regex、regexp或RE),是计算机科学的一个概念。正则表达式使用单个字符串来描述、匹配一系列匹配某个句法规则的字符串。在很多文本编辑器里,正则表达式通常被用来检索、替换那些匹配某个模式的文本。

   Regular Expression的“Regular”一般被译为“正则”、“正规”、“常规”。此处的“Regular”即是“规则”、“规律”的意思,Regular Expression即“描述某种规则的表达式”之意。

re模块操作

  在Python中需要通过正则表达式对字符串进行匹配的时候,可以使用一个模块,名字为re

re模块的使用过程

#coding=utf-8

# 导入re模块
import re

# 使用match方法进行匹配操作
result = re.match(正则表达式,要匹配的字符串)

# 如果上一步匹配到数据的话,可以使用group方法来提取数据
result.group()

  re.match是用来进行正则匹配检查的方法,若字符串匹配正则表达式,则match方法返回匹配对象(Match Object),否则返回None(注意不是空字符串"")。

  匹配对象Macth Object具有group方法,用来返回字符串的匹配部分

re模块示例(匹配以itcast开头的语句)

#coding=utf-8

import re

result = re.match("itcast","itcast.cn")

result.group()

运行结果为:

itcast

说明

  • re.match() 能够匹配出以xxx开头的字符串

正则表达式的规则

表示字符

  上节讲了通过re模块能够完成使用正则表达式来匹配字符串

  本节讲解正则表达式的单字符匹配

字符 功能
. 匹配任意1个字符(除了\n)
[ ] 匹配[ ]中列举的字符
\d 匹配数字,即0-9
\D 匹配非数字,即不是数字
\s 匹配空白,即 空格,tab键
\S 匹配非空白
\w 匹配单词字符,即a-z、A-Z、0-9、_
\W 匹配非单词字符

示例1: .

#coding=utf-8

import re

ret = re.match(".","a")
ret.group()

ret = re.match(".","b")
ret.group()

ret = re.match(".","M")
ret.group()

运行结果:

In [1]: import re

In [2]: ret = re.match('.','a')

In [3]: ret.group()
Out[3]: 'a'

In [4]: ret = re.match('.','b')

In [5]: ret.group()
Out[5]: 'b'

示例2:[ ]

>>> import re
>>> # 如果hello的首字符小写,那么正则表达式需要小写的h
>>> ret = re.match("h","hello Python")
>>> ret.group()
'h'
>>>   # 如果hello的首字符大写,那么正则表达式需要大写的H
>>> ret = re.match("H","Hello Python")
>>> ret.group()
'H'
>>> # 大小写h都可以的情况
>>> ret = re.match("[hH]","hello Python")
>>> ret.group()
'h'
>>> ret = re.match("[hH]","Hello Python")
>>> ret.group() 
'H'
>>> #匹配0到9
>>> ret = re.match("[0123456789]","7Hello Python")
>>> ret.group()
'7'
>>> ret = re.match("[0-9]","7Hello Python")
>>> ret.group()
'7'

示例3:\d

    #coding=utf-8

>>> import re

>>>  # 普通的匹配方式
>>> ret = re.match("嫦娥1号","嫦娥1号发射成功")
>>> ret.group()
'嫦娥1号' 

>>> ret = re.match("嫦娥2号","嫦娥2号发射成功")
>>> ret.group()
'嫦娥2号'


>>> # 使用\d进行匹配
>>> ret = re.match("嫦娥\d号","嫦娥1号发射成功")
>>> ret.group()
'嫦娥1号'

>>> ret = re.match("嫦娥\d号","嫦娥2号发射成功")
>>> ret.group()
'嫦娥2号'


说明:其他几个个匹配符和上面的类似就不举例了。

表示数量

匹配多个字符的相关格式

字符 功能
* 匹配前一个字符出现0次或者无限次,即可有可无
+ 匹配前一个字符出现1次或者无限次,即至少有1次
? 匹配前一个字符出现1次或者0次,即要么有1次,要么没有
匹配前一个字符出现m次
匹配前一个字符至少出现m次
匹配前一个字符出现从m到n次

示例1:*

  需求:匹配出,一个字符串第一个字母为大小字符,后面都是小写字母并且这些小写字母可有可无

#coding=utf-8
>>> import re

>>> ret = re.match("[A-Z][a-z]*","Mm")
>>> ret.group()
'Mm'

>>> ret = re.match("[A-Z][a-z]*","Aabcdef")
>>> ret.group()
'Aabcdef'
>>> 

示例2:+

  需求:匹配出,变量名是否有效

#coding=utf-8
>>>import re

>>> ret = re.match("[a-zA-Z_]+[\w_]*","name1")
>>> ret.group()
'name1'

>>> ret = re.match("[a-zA-Z_]+[\w_]*","_name")
>>> ret.group()
'_name'

>>> ret = re.match("[a-zA-Z_]+[\w_]*","2_name")
>>> ret.group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

示例3:?

需求:匹配出,0到99之间的数字

#coding=utf-8

>>> ret = re.match("[1-9]?[0-9]","7")
>>> ret.group()
'7'
>>> ret = re.match("[1-9]?[0-9]","33")
>>> ret.group()
'33'

>>> ret = re.match("[1-9]?[0-9]","09")
>>> ret.group()
'0'

示例4:{m}

需求:匹配出,8到20位的密码,可以是大小写英文字母、数字、下划线

#coding=utf-8

>>> ret = re.match("[a-zA-Z0-9_]{6}","12a3g45678")
>>> ret.group()
'12a3g4'

>>> ret = re.match("[a-zA-Z0-9_]{8,20}","1ad12f23s34455ff66")
>>> ret.group()
'1ad12f23s34455ff66'
>>> 

表示边界

字符 功能
^ 匹配字符串开头
$ 匹配字符串结尾
\b 匹配一个单词的边界
\B 匹配非单词边界

示例1:$

  需求:匹配163.com的邮箱地址

#coding=utf-8

import re

# 正确的地址
>>> ret = re.match("[\w]{4,20}@163\.com", "xiaoWang@163.com")
>>> ret.group()
'xiaoWang@163.com'

# 不正确的地址
>>> ret = re.match("[\w]{4,20}@163\.com", "xiaoWang@163.comheihei")
>>> ret.group()
'xiaoWang@163.com'

# 通过$来确定末尾
>>> ret = re.match("[\w]{4,20}@163\.com$", "xiaoWang@163.comheihei")
>>> ret.group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

示例2: \b

>>> re.match(r".*\bver\b", "ho ver abc").group()
'ho ver'

>>> re.match(r".*\bver\b", "ho verabc").group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

>>> re.match(r".*\bver\b", "hover abc").group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>>

示例3:\B

>>> re.match(r".*\Bver\B", "hoverabc").group()
'hover'

>>> re.match(r".*\Bver\B", "ho verabc").group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

>>> re.match(r".*\Bver\B", "hover abc").group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

>>> re.match(r".*\Bver\B", "ho ver abc").group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

匹配分组

字符 功能
| 匹配左右任意一个表达式
(ab) 将括号中字符作为一个分组
\num 引用分组num匹配到的字符串
(?P<name>) 分组起别名
(?P=name) 引用别名为name分组匹配到的字符串

示例1:|

  需求:匹配出0-100之间的数字

#coding=utf-8

# 添加|
>>> ret = re.match("[1-9]?\d$|100","8")
>>> ret.group()
'8'

>>> ret = re.match("[1-9]?\d$|100","78")
>>> ret.group()
'78'

>>> ret = re.match("[1-9]?\d$|100","08")
>>> ret.group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

>>> ret = re.match("[1-9]?\d$|100","100")
>>> ret.group()
'100'

示例2:( )

  需求:匹配出163、126、qq邮箱之间的数字

#coding=utf-8

>>> ret = re.match("\w{4,20}@163\.com", "test@163.com")
>>> ret.group()
'test@163.com'

>>> ret = re.match("\w{4,20}@(163|126|qq)\.com", "test@126.com")
>>> ret.group()
'test@126.com'

>>> ret = re.match("\w{4,20}@(163|126|qq)\.com", "test@qq.com")
>>> ret.group()
'test@qq.com'

>>> ret = re.match("\w{4,20}@(163|126|qq)\.com", "test@gmail.com")
>>> ret.group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

示例3:\ 

​ 需求:匹配出<html>hh</html>

#coding=utf-8


# 能够完成对正确的字符串的匹配
>>> ret = re.match("<[a-zA-Z]*>\w*</[a-zA-Z]*>", "<html>hh</html>")
>>> ret.group()
'<html>hh</html>'

# 如果遇到非正常的html格式字符串,匹配出错
>>> ret = re.match("<[a-zA-Z]*>\w*</[a-zA-Z]*>", "<html>hh</htmlbalabala>")
>>> ret.group()
'<html>hh</htmlbalabala>'

# 正确的理解思路:如果在第一对<>中是什么,按理说在后面的那对<>中就应该是什么

# 通过引用分组中匹配到的数据即可,但是要注意是元字符串,即类似 r""这种格式
>>> ret = re.match(r"<([a-zA-Z]*)>\w*</\1>", "<html>hh</html>")
>>> ret.group()
'<html>hh</html>'

# 因为2对<>中的数据不一致,所以没有匹配出来
>>> ret = re.match(r"<([a-zA-Z]*)>\w*</\1>", "<html>hh</htmlbalabala>")
>>> ret.group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

示例4:\number

​ 需求:匹配出<html><h1>www.itcast.cn</h1></html>

#coding=utf-8

>>> ret = re.match(r"<(\w*)><(\w*)>.*</\2></\1>", "<html><h1>www.itcast.cn</h1></html>")
>>> ret.group()
'<html><h1>www.itcast.cn</h1></html>'

>>> ret = re.match(r"<(\w*)><(\w*)>.*</\2></\1>", "<html><h1>www.itcast.cn</h2></html>")
>>> ret.group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

示例5:(?P<name>) (?P=name)

​ 需求:匹配出<html><h1>www.itcast.cn</h1></html>

#coding=utf-8

>>> ret = re.match(r"<(?P<name1>\w*)><(?P<name2>\w*)>.*</(?P=name2)></(?P=name1)>", "<html><h1>www.itcast.cn</h1></html>")
>>> ret.group()
'<html><h1>www.itcast.cn</h1></html>'

>>> ret = re.match(r"<(?P<name1>\w*)><(?P<name2>\w*)>.*</(?P=name2)></(?P=name1)>", "<html><h1>www.itcast.cn</h2></html>")
>>> ret.group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

注意:(?P<name>)(?P=name)中的字母p大写

​ python中的正则表达式基础就这些,下节就能难点了,属于高级篇了。

posted @ 2017-12-31 19:17  杨洛平  阅读(392)  评论(0编辑  收藏  举报