《Python 系列》- 正则表达式

限定范围否定

#输出['xy6b']
#第一个字符:小写字母a-z
#第二个字符:a,b,c,x,y,z
#第三个字符:数字0-9
#第四个字符:不是元音字母
a = 'xy6b'
b = re.findall('[x-z][abcx-z][0-9][^aeiou]', a)
print b

匹配三个字母或两个字母

#输出['xyz', 'abc', 'de']
a = 'xyzabcde'
b = re.findall('[a-z]{2,3}', a)
print b

匹配全部的有效的和无效的html标签

#输出['</body/>']
a = '</body/>'
b = re.findall('</?[^>]+>', a)
print b

匹配任何数字:相当于[0-9],\D则相反

#输出['123']
a = 'xy123'
b = re.findall('\d+', a)
print b

匹配全部字母数字的字符集:相当于[a-zA-Z0-9_],\W则相反

#输出['xy_123']
a = 'xy_123'
b = re.findall('\w+', a)
print b

匹配全部的空格

#输出['y  1']
a = 'xy  123'
b = re.findall('y\s+1', a)
print b

match()函数会从字符串的起始部分对模式进行匹配,匹配成功,则返回一个匹配对象。而匹配对象的group()方法能够显示这个成功的匹配

#若改成afoo on the table,则匹配是吧。输出foo
m = re.match('foo', 'food on the table')
if m is not None:
    print m.group()

search()函数不但会搜索模式在字符串中第一次出现的位置,而且严格地对字符串从左到右搜索

#输出foo
m = re.search('foo', 'afood on the table')
if m is not None:
    print m.group()

匹配多个字符串,使用择一匹配符号(|)

#输出bit
bt = 'bat|bet|bit'
m = re.search(bt, 'He bit me')
if m is not None:
    print m.group()

匹配任何单个字符,点号不能匹配一个换行符(\n)或者非字符,也就是说一个空字符串

#输出bend
anyend = '.end'
m = re.search(anyend, 'bend')
if m is not None:
    print m.group()

对点号转义匹配点号

#输出yyz.
a = 'xyyz.hi'
m = re.search('...\.', a)
if m is not None:
    print m.group()

创建字符集([ ])

#输出xyz
m = re.search('[a-z][xy][a-z]', 'xyz')
if m is not None:
    print m.group()

重复、特殊字符以及分组

#group():以普通方式返回所有匹配部分:abc-123
#groups():返回一个包含所有匹配子字符串的元组:('abc', '123')
#group(1):返回第一个括号匹配的内容:abc
m = re.search('(\w\w\w)-(\d\d\d)', 'abc-123')
print m.groups()
print m.group()
print m.group(1)
print m.group(2)

匹配字符串的起始和结尾以及单词边界

匹配起始

#输出The
m = re.search('^The', 'The end')
if m is not None:
    print m.group()

匹配结尾

#输出Python
m = re.search('Python$','Love Python')
if m is not None:
    print m.group()

匹配边界(有左边界)

#输出the
m = re.search(r'\bthe', 'bit the dog')
if m is not None:
    print m.group()

匹配边界(没有左边界)

#输出the
m = re.search(r'\Bthe', 'bitthe dog')
if m is not None:
    print m.group()

使用findall()和finditer()查找每一次出现的位置

与match()和search()的不同之处,findall()总是返回一个列表。如果没有找到匹配的部分,就返回一个空列表;如果匹配成功,列表将包含所有成功的匹配部分

import re
s = 'This and That'
#[('This', 'That')]
print re.findall(r'(th\w+) and (th\w+)',s,re.I)
#('This', 'That')
print re.finditer(r'(th\w+) and (th\w+)',s,re.I).next().groups()
#This
print re.finditer(r'(th\w+) and (th\w+)',s,re.I).next().group(1)
#[('This', 'That')]
print [g.groups() for g in re.finditer(r'(th\w+) and (th\w+)',s,re.I)]
#['This', 'That']
print re.findall(r'th\w+', s, re.I)
#()
print re.finditer(r'th\w+',s, re.I).next().groups()

使用sub()和subn()搜索与替换

与sub()的区别在于,subn()还返回一个表示替换的总数

#Hello Mr.Smith
print re.sub('X', 'Mr.Smith', 'Hello X')
#XbcdXf
print re.sub('[ae]','X','abcdef')
#('XbcdXf', 2)
print re.subn('[ae]','X','abcdef')

忽略大小写

#['yes', 'Yes', 'YES']
print re.findall(r'(?i)yes','yes?Yes,YES!!')
#Hello Mr.Smith
print re.sub('(?i)x','Mr.Smith','Hello X')

忽略多行,实现跨行搜索

使点号能够匹配\n符号

#['the second line,', 'the third line']
print re.findall(r'th.+','''
                    The first line,
                    the second line,
                    the third line
                ''')

#['the second line,\n    the third line\n']
print re.findall(r'(?s)th.+', '''
    The first line,
    the second line,
    the third line
''')

对部分正则表达式进行分组

#['google.com', 'google.com', 'google.com']
print re.findall(r'http://(?:\w+\.)*(\w+\.com)','http://google.com http://www.google.com http://code.google.com')

使用名称标签

#{'areacode': '800', 'prefix': '555'}
print re.search(r'\((?P<areacode>\d{3})\) (?P<prefix>\d{3})-(?:\d{4})','(800) 555-1212').groupdict()

处理dos环境下tasklist

import re

file = open(r'11.txt','r')
for eachLine in file:
    print re.split(r'\s{3,}',eachLine)

用于正则表达式练习的数据生成器

from random import randrange, choice
from string import ascii_lowercase as lc
from sys import maxint
from time import ctime

tlds = ('com', 'edu', 'net', 'org', 'gov')

for i in xrange(randrange(5,11)):
    dtint = randrange(maxint)
    dtstr = ctime(dtint)
    llen = randrange(4,8)
    login = ''.join(choice(lc) for j in range(llen))
    dlen = randrange(llen,13)
    dom = ''.join(choice(lc) for k in xrange(dlen))
    print '%s::%s@%s.%s::%d-%d-%d' % (dtstr,login,dom,choice(tlds),dtint,llen,dlen)

输出结果如下

Wed Jul 16 14:23:59 2003::dggjtk@yqmlfsrhq.gov::1058336639-6-9
Mon Jan 30 22:24:49 1984::ybxjux@ujlzzsp.gov::444320689-6-7
Tue May 16 10:53:52 2034::oapbiz@axsgjfmuu.gov::2031360832-6-9
Sat Oct 21 19:38:18 2034::memjh@klcbcjtm.net::2045043498-5-8
Thu May 15 02:33:23 1980::fyul@vcqbevzbcrle.gov::327177203-4-12
Sun May 24 22:35:20 1992::efrxqp@ppkookkr.edu::706718120-6-8
Wed Sep 08 13:25:14 1982::dlorsf@bdwpexjajjke.com::400310714-6-12
Thu Sep 03 16:05:54 1992::xidiv@yquiyfmmikgl.org::715507554-5-12
Thu Aug 30 10:39:13 2018::mufzix@hmhhiicleky.com::1535596753-6-11
Wed Jul 16 02:47:02 2008::aqhu@lbahtrf.gov::1216147622-4-7

匹配所有日期

import re
data = 'Sun Feb 09 04:11:47 2003::kddba@nsmxoqrmwayy.net::1044735107-5-12'
patt1 = '^Mon|^Tue|^Wed|^Thu|^Fri|^Sat|^Sun'
patt2 = '^(\w{3})'
file = open('readme.txt','r')
for i in file:
    print re.match(patt2,i).group()

搜索与匹配,还是贪婪

我们可以发起一个搜索,因为我们知道我们想要查找的内容

import re
data = 'Sun Feb 09 04:11:47 2003::kddba@nsmxoqrmwayy.net::1044735107-5-12'
file = open('readme.txt','r')
for i in file:
    print re.search('\d+-\d+-\d+',i).group()

我们也可以创建一个正则表达式匹配整个行,然后使用子组保存想要的数据

import re
data = 'Sun Feb 09 04:11:47 2003::kddba@nsmxoqrmwayy.net::1044735107-5-12'
file = open('readme.txt','r')
for i in file:
    print re.match('.+(\d+-\d+-\d+)',i).group(1)

但是贪婪试图获取匹配改模式的尽可能多的字符,那就是使用非贪婪

import re
data = 'Sun Feb 09 04:11:47 2003::kddba@nsmxoqrmwayy.net::1044735107-5-12'
file = open('readme.txt','r')
for i in file:
    print re.match('.+?(\d+-\d+-\d+)',i).group(1)

其他

data = 'Sun Feb 09 04:11:47 2003::kddba@nsmxoqrmwayy.net::1044735107-5-12'
print re.search('(.+?)\d{4}?',data).group(1)
print re.search('::(\w+@\w+.\w{3})',data).group(1)
print re.search('\w{3}\s(\w{3})',data).group(1)
print re.search('(\w{4})::',data).group(1)
print re.search('(\d{2}:\d{2}:\d{2})',data).group(1)
print re.search('::(\w+)@',data).group(1)
print re.search('@(\w+)',data).group(1)
print re.sub('::(\w+@\w+.\w{3}).+','jinxx@126.com',data)

 

转载于:https://my.oschina.net/kimisme/blog/1603198

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值