正则表示小记

2019.04.24


re中一般用''区分自定义字符,这个与在字符传中相同的字母和目的的字符串冲突,e.g.'\\'用来表示"\",因为每个''都是"\"
解决方法: re中用r表示raw string.也就是说r"\n"代表''和'n'这两个字符

re.escape(pattern)
忽略在pattern中的某些特定的字符, 也就是说不包含metacharacter(在计算机中有特定含义的字符,例如\,*,+,(,{,|,^,$等)
e.g. (python3.6)
>>> import re
>>> re.escape('^a.*s')
'\\^a\\.\\*s'
>>> re.escape('python.exe')
'python\\.exe'
在py3.3之后,'_'不会被escaped,也就是说,下面这两种sub的表达方式一致:
>>> re.sub('a', re.escape('_'), 'aa')
'__'
>>> re.sub('a', lambda _:'_', 'aa')
'__'
>>> 
*但是,与sub()和subn(),escape一般不用在中间
re.I: 代表忽略大小写
re.compile(pattern,flags=0):将正则表达模式编译成一个正则表达对象, 这个对象可以用在match(),search()或者其他方法中进行匹配.

prog = re.compile(pattern)
result=prog.match(string)
与
result=re.match(pattern, string)
等价
但是,当同一个模式多次匹配的时候,上面的compile方式会更有效率
re.finditer(pattern, string, flags=0) or pattern_object.finditer(string, flags=0)

返回一个iterator,为string中没有重叠的匹配pattern的match objects, 传回顺序为string由左到右按照顺序匹配的顺序
Match.start([group]) 返回该group匹配的子字符串的起始未知的位置index, group参数默认为0,也就是整个匹配的字符串
Match.end([group])同理,返回的是结束未知的index

>>> email = "tony@tiremove_thisger.net"
>>> m = re.search("remove_this", email)
>>> email[:m.start()] + email[m.end():]
'tony@tiger.net'
posted @ 2019-04-24 09:55  lily19  阅读(136)  评论(0编辑  收藏  举报