Python学习笔记(十):Python正则表达式

http://developer.51cto.com/art/201003/188586.htm

Python正则表达式十种相关的匹配方法


Python正则表达式需要各种各样的匹配,但是我们不能盲目的进行相匹配,下面就向大家介绍经常遇到的十种Python正则表达式匹配方式,希望大家有所收获。

1.测试Python正则表达式是否 匹配字符串的全部或部分

 
 
  1. regex=ur"..." #正则表达式  
  2. if re.search(regex, subject):  
  3. do_something()  
  4. else:  
  5. do_anotherthing() 

2.测试Python正则表达式是否匹配整个字符串

 
 
  1. regex=ur"...\Z" #正则表达式末尾以\Z结束  
  2. if re.match(regex, subject):  
  3. do_something()  
  4. else:  
  5. do_anotherthing() 

3. 创建一个匹配对象,然后通过该对象获得匹配细节

 
 
  1. regex=ur"..." #正则表达式  
  2. match = re.search(regex, subject)  
  3. if match:  
  4. # match start: match.start()  
  5. # match end (exclusive): match.end()  
  6. # matched text: match.group()  
  7. do_something()  
  8. else:  
  9. do_anotherthing() 

4.获取Python正则表达式所匹配的子串

 
 
  1. regex=ur"..." #正则表达式  
  2. match = re.search(regex, subject)  
  3. if match:  
  4. result = match.group()  
  5. else:  
  6. result = "" 

5. 获取捕获组所匹配的子串

 
 
  1. regex=ur"..." #正则表达式  
  2. match = re.search(regex, subject)  
  3. if match:  
  4. result = match.group(1)  
  5. else:  
  6. result = "" 

6. 获取有名组所匹配的子串

 
 
  1. regex=ur"..." #正则表达式  
  2. match = re.search(regex, subject)  
  3. if match:  
  4. result = match.group("groupname")  
  5. else:  
  6. result = "" 

7. 将字符串中所有匹配的子串放入数组中

 
 
  1. reresult = re.findall(regex, subject) 

8.遍历所有匹配的子串

 
 
  1. (Iterate over all matches in a string)  
  2. for match in re.finditer(r"<(.*?)\s*.*?/\1>", subject)  
  3. # match start: match.start()  
  4. # match end (exclusive): match.end()  
  5. # matched text: match.group() 

9.通过Python正则表达式 字符串创建一个正则表达式对象

 
 
  1. (Create an object to use the same regex for many 
    operations)  
  2. rereobj = re.compile(regex) 

10.用法1的Python正则表达式对象版本

 
 
  1. rereobj = re.compile(regex)  
  2. if reobj.search(subject):  
  3. do_something()  
  4. else:  
  5. do_anotherthing() 

以上就是对Python正则表达式相关问题匹配的解决方案。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值