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

来源:互联网 发布:广州疯狂java在哪 编辑:程序博客网 时间:2024/06/11 00:32
在前面学习过正则表达式有一些标志,可以通过编译时添加进去。比如学习过的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/

原创粉丝点击