Quick Start
Import Repattern = ' 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]))
Execution Result:
#python re_simple_match.py Found ' This ' in ' Does this text match the pattern? ' From 5 to 9 ("this") import re# precompile the patternsregexes = [Re.compile (p) for p in (' This ', ' that ')]text = ' Does thi S 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))
Execution Result:
#python re_simple_compiled.py text:does This Text match the pattern? Seeking "this", match! Seeking "that" and no match!import retext = ' abbaaabbbbaaaaa ' pattern = ' ab ' for match in Re.findall (pattern, text): p Rint (' Found ' {0} '. Format (Match))
Execution Result:
#python re_findall.py Found "AB" Found "ab" Import retext = ' 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))
Execution Result:
#python re_finditer.py Found "AB" at 0:2found "AB" at 5:7