易截截图软件、单文件、免安装、纯绿色、仅160KB

Python正则表达式的常用匹配用法


下面列出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.创建一个匹配对象,然后通过该对象获得匹配细节(Create an object with details about how the regex matches (part of) a string)
regex=ur"" #正则表达式
match = re.search(regex, subject)
if match:
    # match start: match.start()
    # match end (exclusive): atch.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


相关文档:

Python和Decorator(装饰器)模式

先给出一个四人团对
Decorator mode
的定义:
动态地
给一个
对象
添加一些
额外的职责

 
再来说说这个模式的好处:认证,权限检查,记日志,检查参数,加锁,等等等等,这些功能和系统业务无关,但又是系统所必须的,说的更明白一点,就是面向方面的编程(
AOP
)。
AOP
把与业务无关的代码十分干净 ......

Python中Range和XRange的区别

Python中Range和XRange的区别(Difference between Range and XRange in Python)
最近机器出了点问题,所以一直没有写新的东西出来。之前在读Python的代码的时候,发觉好多人喜欢用XRange,而不是Range,我也只是记得学习的时候开始学到的是Range,后面又看到有个XRange,当时也没有深究,为什么Python里面要有两个同样的功 ......

[python]PLY模块 Lex/YACC的python实现

  PLY模块 是Lex/YACCPython 的实现,可以用来实现词法分析/语法分析,但如何用,还没研究,以后有时间再研究吧;
  主页: http://www.dabeaz.com/ply/
  pycparser模块 是使用PLY模块分析c语言语法的模块,没什么文档,但模块自带了例子和测试用例。
   主页: http://code.google.com/p/pycpa ......

python 集合运算

集合类型操作符(所有的集合类型)
联合( | )
联合(union)操作和集合的OR(又称可兼析取(inclusive
disjunction))其实是等价的,两个集
合的联合是一个新集合,该集合中的每个元素都至少是其中一个集合的成员,即,属于两个集合其

之一的成员。联合符号有一个等价的方法,union().
Edit By Vheavens
Edit By Vhe ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号