graceting

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1,贪婪和非贪婪模式

重复运算符默认是贪婪的,即会进行尽可能多的匹配

代码示例:

>>> import re
>>> emphasis_pattern = re.compile(r'''
\*          #beginning emphais tag --an asterisk
(           #begin group for capturing phrase
[^\*]+      #capture anything except asterisks
)           #end group
\*          #ending emphasis tag
''', re.VERBOSE)
>>> re.sub(emphasis_pattern, r'<em>\1</em>', 'Hello,*world*!')
'Hello,<em>world</em>!'
>>> emphasis_pattern= r'\*(.+)\*'
>>> re.sub(emphasis_pattern, r'<em>\1</em>', '*This* is *a boy!*')
'<em>This* is *a boy!</em>'

##让正则表达式变的更加易读的方式是在re函数中使用VERBOSE标志,这样可在模式中添加空白

##使用compile函数处理了正则表达式,让处理过程更有效率,将正则表达式转换为模式对象

将贪婪模式变换为非贪婪模式:只需要在重复运算符后面加上一个问号即可

代码示例:

>>> emphasis_pattern= r'\*(.+?)\*'
>>> re.sub(emphasis_pattern, r'<em>\1</em>', '*This* is *a boy!*')
'<em>This</em> is <em>a boy!</em>'

 

 

posted on 2014-03-28 16:57  IT-tingting  阅读(860)  评论(0)    收藏  举报