快速入门
import re pattern = 'this' text = 'Does this text match the pattern?' match = re.search(pattern,text) s = match.start() e = match.end() print('Found "{0}"\nin "{1}"'.format(match.re.pattern,match.string)) print('from {0} to {1} ("{2}")'.format( s,e,text[s:e]))
执行结果:
#python re_simple_match.py Found "this" in "Does this text match the pattern?" from 5 to 9 ("this") import re # Precompile the patterns regexes = [ re.compile(p) for p in ('this','that')] text = 'Does this text match the pattern?' print('Text: {0}\n'.format(text)) for regex in regexes: if regex.search(text): result = 'match!' else: result = 'no match!' print('Seeking "{0}" -> {1}'.format(regex.pattern,result))
执行结果:
#python re_simple_compiled.py Text: Does this text match the pattern? Seeking "this" -> match! Seeking "that" -> no match! import re text = 'abbaaabbbbaaaaa' pattern = 'ab' for match in re.findall(pattern,text): print('Found "{0}"'.format(match))
执行结果:
#python re_findall.py Found "ab" Found "ab" import re text = 'abbaaabbbbaaaaa' pattern = 'ab' for match in re.finditer(pattern,text): s = match.start() e = match.end() print('Found "{0}" at {1}:{2}'.format(text[s:e],s,e))
执行结果:
#python re_finditer.py Found "ab" at 0:2 Found "ab" at 5:7
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。