一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python正则表达式学习笔记

时间:2012-11-13 编辑:简简单单 来源:一聚教程网

就个人而言,主要用它来做一些复杂字符串分析,提取想要的信息
学习原则:够用就行,需要的时候在深入

现总结如下:

正则表达式中特殊的符号:

“.” 表任意字符
“^ ” 表string起始
“$” 表string 结束
“*” “+” “?” 跟在字符后面表示,0个——多个, 1个——多个, 0个或者1个
*?, +?, ?? 符合条件的情况下,匹配的尽可能少//限制*,+,?匹配的贪婪性
{m} 匹配此前的字符,重复m次
{m,n} m到n次,m,n可以省略

举个例子 ‘a.*b’ 表示a开始,b结束的任意字符串
a{5} 匹配连续5个a

[] 表一系列字符 [abcd] 表a,b,c,d [^a] 表示非a
| A|B 表示A或者B , AB为任意的正则表达式 另外|是非贪婪的如果A匹配,则不找B
(…) 这个括号的作用要结合实例才能理解, 用于提取信息

d [0-9]
D 非 d
s 表示空字符
S 非空字符
w [a-zA-Z0-9_]
W 非 w

一:re的几个函数

1: compile(pattern, [flags])
根据正则表达式字符串 pattern 和可选的flags 生成正则表达式 对象

生成正则表达式 对象(见二)

其中flags有下面的定义:
I 表示大小写忽略
L 使一些特殊字符集,依赖于当前环境
M 多行模式 使 ^ $ 匹配除了string开始结束外,还匹配一行的开始和结束
S “.“ 匹配包括‘n’在内的任意字符,否则 . 不包括‘n’
U Make w, W, b, B, d, D, s and S dependent on the Unicode character properties database
X 这个主要是表示,为了写正则表达式,更可毒,会忽略一些空格和#后面的注释

其中S比较常用,
应用形式如下
import re
re.compile(……,re.S)

2: match(pattern,string,[,flags])
让string匹配,pattern,后面分flag同compile的参数一样
返回MatchObject 对象(见三)

3: split( pattern, string[, maxsplit = 0])
用pattern 把string 分开
>>> re.split(‘W+’, ‘Words, words, words.’)
['Words', 'words', 'words', '']
括号‘()’在pattern内有特殊作用,请查手册

4:findall( pattern, string[, flags])
比较常用,
从string内查找不重叠的符合pattern的表达式,然后返回list列表

5:sub( pattern, repl, string[, count])
repl可以时候字符串,也可以式函数
当repl是字符串的时候,
就是把string 内符合pattern的子串,用repl替换了

当repl是函数的时候,对每一个在string内的,不重叠的,匹配pattern
的子串,调用repl(substring),然后用返回值替换substring

>>> re.sub(r’defs+([a-zA-Z_][a-zA-Z_0-9]*)s*(s*):’,
… r’static PyObject*npy_1(void)n{‘,
… ‘def myfunc():’)
‘static PyObject*npy_myfunc(void)n{‘

>>> def dashrepl(matchobj):
… if matchobj.group(0) == ‘-’: return ‘ ‘
… else: return ‘-’
>>> re.sub(‘-{1,2}’, dashrepl, ‘pro—-gram-files’)
‘pro–gram files’

二:正则表达式对象 (Regular Expression Objects )

产生方式:通过 re.compile(pattern,[flags])回

match( string[, pos[, endpos]]) ;返回string[pos,endpos]匹配
pattern的MatchObject(见三)

split( string[, maxsplit = 0])
findall( string[, pos[, endpos]])
sub( repl, string[, count = 0])
这几个函数和re模块内的相同,只不过是调用形式有点差别

re.几个函数和 正则表达式对象的几个函数,功能相同,但同一程序如果
多次用的这些函数功能,正则表达式对象的几个函数效率高些

三:matchobject

通过 re.match(……) 和 re.compile(……).match返回

该对象有如下方法和属性:

方法:
group( [group1, ...])
groups( [default])
groupdict( [default])
start( [group])
end( [group])

说明这几个函数的最好方法,就是举个例子

matchObj = re.compile(r”(?Pd+).(d*)”)
m = matchObj.match(’3.14sss’)
#m = re.match(r”(?Pd+).(d*)”, ’3.14sss’)

print m.group()
print m.group(0)
print m.group(1)
print m.group(2)
print m.group(1,2)

print m.group(0,1,2)
print m.groups()
print m.groupdict()

print m.start(2)
print m.string

输出如下:
3.14
3.14
3
14
(’3′, ’14′)
(’3.14′, ’3′, ’14′)
(’3′, ’14′)
{‘int’: ’3′}
2
3.14sss

所以group() 和group(0)返回,匹配的整个表达式的字符串
另外group(i) 就是正则表达式中用第i个“()” 括起来的匹配内容
(’3.14′, ’3′, ’14′)最能说明问题了。

 

字符串替换
1.替换所有匹配的子串
用newstring替换subject中所有与正则表达式regex匹配的子串

result, number = re.subn(regex, newstring, subject)2.替换所有匹配的子串(使用正则表达式对象)
reobj = re.compile(regex)
result, number = reobj.subn(newstring, subject)字符串拆分
1.字符串拆分
result = re.split(regex, subject)2.字符串拆分(使用正则表示式对象)
reobj = re.compile(regex)
result = reobj.split(subject)匹配


下面列出Python正则表达式的几种匹配用法:

1.测试正则表达式是否匹配字符串的全部或部分
regex=ur"..." #正则表达式
if re.search(regex, subject):
    do_something()
else:
    do_anotherthing()

2.测试正则表达式是否匹配整个字符串
regex=ur"...Z" #正则表达式末尾以Z结束
if re.match(regex, subject):
    do_something()
else:
    do_anotherthing()

3. 创建一个匹配对象,然后通过该对象获得匹配细节
regex=ur"..." #正则表达式
match = re.search(regex, subject)
if match:
    # match start: match.start()
    # match end (exclusive): match.end()
    # matched text: match.group()
    do_something()
else:
    do_anotherthing()

4.获取正则表达式所匹配的子串
(Get the part of a string matched by the regex)

regex=ur"..." #正则表达式
match = re.search(regex, subject)
if match:
    result = match.group()
else:
    result = ""

5. 获取捕获组所匹配的子串
(Get the part of a string matched by a capturing group)

regex=ur"..." #正则表达式
match = re.search(regex, subject)
if match:
    result = match.group(1)
else:
    result = ""

6. 获取有名组所匹配的子串
(Get the part of a string matched by a named group)

regex=ur"..." #正则表达式
match = re.search(regex, subject)
if match:
    result = match.group("groupname")
else:
    result = ""

7. 将字符串中所有匹配的子串放入数组中
(Get an array of all regex matches in a string)

result = re.findall(regex, subject)8.遍历所有匹配的子串
(Iterate over all matches in a string)

for match in re.finditer(r"<(.*?)s*.*?/1>", subject)
    # match start: match.start()
    # match end (exclusive): match.end()
    # matched text: match.group()9.通过正则表达式字符串创建一个正则表达式对象
(Create an object to use the same regex for many operations)

reobj = re.compile(regex)

10.用法1的正则表达式对象版本
(use regex object for if/else branch whether (part of) a string can be matched)

reobj = re.compile(regex)
if reobj.search(subject):
    do_something()
else:
    do_anotherthing()

11.用法2的正则表达式对象版本
(use regex object for if/else branch whether a string can be matched entirely)

reobj = re.compile(r"Z") #正则表达式末尾以Z 结束
if reobj.match(subject):
    do_something()
else:
    do_anotherthing()

12.创建一个正则表达式对象,然后通过该对象获得匹配细节
(Create an object with details about how the regex object matches (part of) a string)

reobj = re.compile(regex)
match = reobj.search(subject)
if match:
    # match start: match.start()
    # match end (exclusive): match.end()
    # matched text: match.group()
    do_something()
else:
    do_anotherthing()

13.用正则表达式对象获取匹配子串
(Use regex object to get the part of a string matched by the regex)

reobj = re.compile(regex)
match = reobj.search(subject)
if match:
    result = match.group()
else:
    result = ""

14.用正则表达式对象获取捕获组所匹配的子串
(Use regex object to get the part of a string matched by a capturing group)

reobj = re.compile(regex)
match = reobj.search(subject)
if match:
    result = match.group(1)
else:
    result = ""

15.用正则表达式对象获取有名组所匹配的子串
(Use regex object to get the part of a string matched by a named group)

reobj = re.compile(regex)
match = reobj.search(subject)
if match:
    result = match.group("groupname")
else:
    result = ""

16.用正则表达式对象获取所有匹配子串并放入数组
(Use regex object to get an array of all regex matches in a string)

reobj = re.compile(regex)
result = reobj.findall(subject)17.通过正则表达式对象遍历所有匹配子串
(Use regex object to iterate over all matches in a string)

reobj = re.compile(regex)
for match in reobj.finditer(subject):
    # match start: match.start()
    # match end (exclusive): match.end()
    # matched text: match.group()

非贪婪、多行匹配正则表达式例子


一些regular的tips:

1 非贪婪flag

>>> re.findall(r"a(d+?)", "a23b")
        ['2']
>>> re.findall(r"a(d+)", "a23b")
        ['23']注意比较这种情况:

>>> re.findall(r"a(d+)b", "a23b")
        ['23']
>>> re.findall(r"a(d+?)b", "a23b")
        ['23']

2 如果你要多行匹配,那么加上re.S和re.M标志
re.S:.将会匹配换行符,默认.不会匹配换行符

>>> re.findall(r"a(d+)b.+a(d+)b", "a23bna34b")
        []
>>> re.findall(r"a(d+)b.+a(d+)b", "a23bna34b",

re.S)
        [('23', '34')]
>>>re.M:^$标志将会匹配每一行,默认^和$只会匹配第一行

>>> re.findall(r"^a(d+)b", "a23bna34b")
        ['23']
>>> re.findall(r"^a(d+)b", "a23bna34b", re.M)
        ['23', '34']但是,如果没有^标志,

>>> re.findall(r"a(d+)b", "a23bna23b")
        ['23', '23']可见,是无需re.M

热门栏目