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
相关文档:
源代码下载:下载地址在这里
# 032
# 其实cPickle这个模块起到的作用可以用“完美地协调了文件中的内容(对象)和代码中的引用”来形容
import cPickle as p # 这条语句给cPickle起了个小名p
objectFileName = r'C:\Data.txt'
aList = [1, 2, 3]
f = file(objectFileName, 'w')
p.dump(aList, f)
f.close ......
源代码下载:下载地址在这里
# 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! ......
源代码下载:下载地址在这里
# 039
while True:
try:
x = int(raw_input('Input a number:'))
y = int(raw_input('Input a number:'))
z = x / y
except ValueError, ev:
print 'That is not a valid number.', ev
except ZeroDivisionError, ez:
print 'Di ......
说实话,Python真的不太适合做这种二进制的东西,天生没有指针,导致在C/C++很容易的东西在Python下就很麻烦。不过好像3.1有了原生的bytes类型,不知道能不能改变现状。
import sys
import time
import socket
import struct
import random
def SendPacketData (Buffer = None , DestIP = "127.0.0.1" , DestPort = 0 ......
学习Python的道路漫漫,光看不练比较无聊。
找了个网页,上面有几道习题,无聊之余拿来练手,还有些乐趣。
是这里:http://www.cnblogs.com/belaliu/archive/2006/11/25/572140.html
注:习题后面贴的代码不一定是最优的。
大部分比较好解决,有点难度的是第4题做去除字符串内的空格的操作。
找了网上的解决方案,有这 ......