正则表达式的作用我就不赘述了,首先讲解一下单个字符的匹配。
1、‘’.“(点):匹配除了(\n)之外的所有字符。
首先import re,以下的示例都默认已经导入了re包,不再另行说明。
- string1 = 'python'
- string2 = '012345'
- ma1 = re.match(r'.',string1)
- ma2 = re.match(r'.',string2)
- print ma1.group()
2、‘’[...]‘’(中括号):匹配中括号中的任意字符集。
- ma = re.match(r'[p]',string1)
- print ma.group()
- ma = re.match(r'[a-z]',string1)
- print ma.group()
- string3 = 'PYTHON'
- ma = re.match(r'[A-Z]',string3)
- print ma.group()
- ma = re.match(r'[0-9]',string2)
- print ma.group()
- ma = re.match(r'[a-zA-Z0-9]',string1)
- print ma.group()
3、\d 和 \D :匹配数字/非数字
- string4 = '[];;:'
- ma1 = re.match(r'\D',string4)
- ma2 = re.match(r'\d',string2)
- print ma1.group()
- print ma2.group()
4、\s 和 \S 同上,分别匹配空白和非空白字符
5、\w 和 \W 同上,分别匹配单词字符[a-zA-Z0-9]和非单词字符
6、匹配带[ ]的字符集时,需要在正则表达式中加上转义符 \
7、* (星号):匹配0到无穷次
- ma = re.match(r'[a-z][a-z]*',string1)
- print ma.group()
8、+ (星号):匹配1到无穷次
- ma = re.match(r'[a-z][a-z]+',string1)
- print ma.group()
9、? (星号):匹配0到1次,即有或无
- ma = re.match(r'[a-z][a-z]?',string1)
- print ma.group()
10、{m,n} :匹配出现m到n次的字符串
- ma = re.match(r'[\w]{1,4}',string1)任意字母和数字出现1到4次
- print ma.group()
11、*? 和 +? 和 ?? :非贪婪模式匹配,即最少匹配。仅举一例。
- ma = re.match(r'[\w][\w]+?',string1)
- print ma.group()
12、^ 和 $ :分别匹配开始和结束。例如下例,可以成功匹配网易126的邮箱,但是如果string5='alibee@126.comabc'而
没有$符号时,也能匹配成功,但此时的string5不是一个符合规则的网易邮箱账号。
- string5 = 'alibee@126.com'
- ma = re.match(r'^[\w]{1,6}@126.com$',string5)
- print ma.group()
13、\A 和 \Z :分别匹配以指定的字符开始和结尾。下例表示以a开头的字符串,\Z的用法还没明白,有明白的朋友请解惑
- ma = re.match(r'\Aa[\w]+@126.com',string5)
- print ma.group()
14、| :表示或者,下例表示ab或者d都可以匹配
- ma = re.match(r'ab|d','d')
- print ma.group()
15、() :表示元组,下例表示即可匹配126邮箱,也可以匹配163邮箱
- string5 = 'alibee@126.com'
- ma = re.match(r'alibee@(126|163).com',string5)
- print ma.group()
16、:匹配中文
- ma = re.match(r'[\u4e00-\u9fa5] ','安定飞’)</span>
以上基本包含了常用的正则表达式语法,下面简单介绍python中re包的几个方法。
1、search(pattern,string,flag):pattern中可以是正则表达式,flag 可以省略,search方法只能查找一个。
- ma = re.search(r'[\w]+',string5)
- print ma.group()
2、findall(pattern,string,flag) :找到所有符号pattern的字符串,flag可以省略。
- string7 = '1,2,3,4'
- ma = re.findall(r'\d+',string7)
- print ma #['1', '2', '3', '4']
3、sub(pattern,repl,string,count,flag):将repl替换成string,repl可以接字符串,也可以是函数返回值。
- string8 = '5'
- ma = re.sub(r'\d+','6',string8)
- print ma
- def addnumber(match) :
- num = match.group()
- num = int(num)+1
- return str(num)
- ma = re.sub(r'\d+',addnumber,string8)
- print ma
4、split(pattern,string) :以pattern分割string,返回分割结果组成的列表。
- ma = re.split(r',',string7)
- print ma
以上的内容只是粗浅的学习正则表达式,更多用法请参考:https://msdn.microsoft.com/zh-cn/library/ae5bf541(VS.80).aspx