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 ......
源代码下载:下载地址在这里
# 037
fileName = ''
while 1:
fileName = raw_input("Input a file name:")
if fileName == 'q':
break
try:
f = file(fileName, 'r')
print 'Opened a file.'
except:
print 'There is no file named', fileName
......
可以播放大部分的音视频.
demo download: http://www.sandy1219.com/python/media.rar
playMP3.py
# -*- coding: utf-8 -*-
import wx;
import wx.media;
import os;
import SPrint;
import mediaStateBar;
import mediaList;
import SaveLog;
import MediaItem;
woldcart = "media files|*.*|avi ......
验证是否已经安装了MySQLdb:
==========================================================
d:\usr\local\Python25>python
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] onwin32
Type "help", "copyright", "credits" or "license" for ......
python string和PyQt的QString的区别 以下在Python2.6和PyQt4.4.4 for
Python2,6环境下讨论: Python中有两种有关字符的类型:Python string object和Python Unicode
object。主要使用Python string object进行数据输入输出。 PyQt中与之相对应的字符有关类
python string和PyQt的QString的区别
以下在Python2.6和PyQt4 ......