python里使用正则表达式的内嵌功能选项标志

在前面学习过正则表达式有一些标志,可以通过编译时添加进去。比如学习过的re.DOTALL标志,这些标志都是在编译设置的,如果不是立即编译正则表达式时,就不能使用这些参数。比如你需要把一个正则表达式当作参数传送给别的函数时,就比较麻烦,不仅要传送正则表达式,还需要传送选项标志。如果开发人员不小心,把一个参数搞丢了,或者搞错了,就容易出错,这时怎么办呢?显然有更好的方式,就是把选项参数融入正则表达式里,这样就达到原子一致性,要丢就一起丢,不会出现半桶水的样子。如下面例子:
[python]  view plain  copy
  1. #python 3.6  
  2. #蔡军生   
  3. #http://blog.csdn.net/caimouse/article/details/51749579  
  4. #  
  5. import re  
  6.   
  7. text = 'This is some text -- with punctuation.'  
  8. pattern = r'\bT\w+'  
  9. regex = re.compile(pattern)  
  10.   
  11. print('Text      :', text)  
  12. print('Pattern   :', pattern)  
  13. print('Matches   :', regex.findall(text))  
  14.   
  15.   
  16. print('\n(?i):')  
  17. pattern = r'(?i)\bT\w+'  
  18. regex = re.compile(pattern)  
  19.   
  20. print('Text      :', text)  
  21. print('Pattern   :', pattern)  
  22. print('Matches   :', regex.findall(text))  

结果输出如下:
Text      : This is some text -- with punctuation.
Pattern   : \bT\w+
Matches   : ['This']


(?i):
Text      : This is some text -- with punctuation.
Pattern   : (?i)\bT\w+

Matches   : ['This', 'text']

在这个例子里,就是添加(?i)在正则表达式里面表示不对大小字母敏感。


标志        对应的字母
ASCII         a
IGNORECASE     i
MULTILINE     m
DOTALL         s

VERBOSE         x





宁波整形美容医院 http://www.lyxcl.org/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值