易截截图软件、单文件、免安装、纯绿色、仅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中数据结构 列表 元组 字典 序列


列表
list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个 序列
的项目。假想你有一个购物列表,上面记载着你要买的东西,你就容易理解列表了。只不过在你的购物表上,可能每样东西都独自占有一行,而在Python中,
你在每个项目之间用逗号分割。
列表中的项目应该包括在方括号中,这样Python就知道你是 ......

Python和Singleton (单件)模式

我知道的一种在
python

Singleton mode
的实现如下:
class Foo: pass
def
instance():
   
global inst
   
try:
       
inst
   
except:
       
inst =
Foo
()
&n ......

Python中Range和XRange的区别

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

python安装之setuptools

David 在本文中将带领我们了解一下 setuptools 框架,它是 Python Enterprise Application Kit(PEAK)的一个副项目。 setuptools 替换了标准的 distutils 库,并为 Python 添加了版本化的包和依赖性管理。Perl 用户比较熟悉 CPAN,而 Ruby 用户则比较熟悉 Gems;引导 setuptools 的 ez_setup 工具和随之而生的扩展后的 eas ......

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

  PLY模块 是Lex/YACCPython 的实现,可以用来实现词法分析/语法分析,但如何用,还没研究,以后有时间再研究吧;
  主页: http://www.dabeaz.com/ply/
  pycparser模块 是使用PLY模块分析c语言语法的模块,没什么文档,但模块自带了例子和测试用例。
   主页: http://code.google.com/p/pycpa ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号