python笔记之正则表达式
正则表达式
具体的参考手册,这里记下一些小问题:
1、re对象的方法
match Match a regular expression pattern to the beginning of a string.
search re.search(pattern, string, flags) flags:re.I re.M re.X re.S re.L re.U
sub Substitute occurrences of a pattern found in a string.
subn Same as sub, but also return the number of substitutions made.
split Split a string by the occurrences of a pattern.
findall Find all occurrences of a pattern in a string.
finditer Return an iterator yielding a match object for each match.
iter = re.finditer("23", "123423523")
for i in iter:
print i.span()
compile 将一个pattern编译成一个RegexObject.
re对象的使用方法,reobject = re.complie(pattern),从reobject获得pattern的方法,使用reobject.pattern属性
如果一个reobject要多次使用,最好使用compile方法提高性能,否则可以直接按这种方式使用,re.search(pattern, string)
purge Clear the regular expression cache.
escape Backslash all non-alphanumerics in a string.
2、要使group(s)方法,应该在pattern中对想要在tuples中的部分加上括号,例如“123-45”,想匹配这个string,但是只想获得前三个数字,则可以使用这样的pattern,"(\d{3})-\d{2}"
,注意前面使用了括号,再调用groups方法会得到tuples,("123",)
。group(s)是SRE_Match object 的方法,通常使用方法为reobject.search(string).group(s)
3、要匹配任意单个字符使用".",任意个字符使用".*"(包括0个),或者".+"(至少一个)。
4、括号的多种用法
(?:)不放入groups中
(?iLmsux) 为pattern加入I,L,M,S,U,X标志
(?P<name>) 为group的一项加入别名
(?P=name) 匹配在之前用name表示的部分表达式所匹配到的内容
(?#comment) 注释
test1(?=test2) 如果test1后面跟着te
相关文档:
源代码下载:下载地址在这里
# 033
class Person:
age = 22
def sayHello(self): # 方法与函数的区别在于需要一个self参数
print 'Hello!'
# end of def
# end of class # 这是我良好的编程风格
p = Person()
print p.age
p.sayHello()
output:
22
Hello! ......
源代码下载:下载地址在这里
# 035
class Person:
population = 0 #这个变量是属于整个类的
def __init__(self, name):
self.name = name
print '初始化 %s' % self.name
Person.population += 1
# end of def
def __del__(self):
print '%s says bye.' % self. ......
首先是下载python3,现在的最高版本是3.1.1
for linux。
我的放置路径是/home/python下放置Python-3.1.1.tgz,执行以下系列操作:
1.解压:tar zxvf Python-3.1.1.tgz----生成解压包Python-3.1.1
2.转换到Python-3.1.1路径下,执行./configure
3.make
4.make install
在rehl5中已经默认安装了python2.4,所以要做如下 ......
copy模块用于对象的拷贝操作。该模块非常简单,只提供了两个主要的方法:
copy.copy
与
copy.deepcopy
,分别表示浅复制与深复制。什么是浅复制,什么是深复制,网上有一卡车一卡车的资料,这里不作详细介绍。复制操作只对复合对象有效。用简单的例子来分别介绍这两个方法。
浅复制只复制对象本身,没有复制该对象 ......
——由于最近在做有关网页搜索的项目,涉及到一些编码方面的知识,小弟在网上偶然地发现了这么一篇文章,很易懂,不晦涩,为了方便自己也同时能方便大家,就转了过来,以作参考……
文章出处:http://blog.csdn.net/tingsking18/arc ......