Advanced Lesson 1
Regular Expressions
Chapter 6: Implementing regular expressions
Pre-compiling patterns
The re
module also offers an object-oriented way to perform your regular expression searches.
You can pre-compile your pattern string into a Pattern
object. You can then perform all of the actions like search()
and match()
as methods of Pattern
instead of functions. Look at the documentation to see what methods/attributes Pattern
has on offer!
>>> string = "morning morning morning world!"
>>> pattern = re.compile("morning")
>>> type(pattern)
<class 're.Pattern'>
>>> pattern.pattern
'morning'
>>> pattern.match(string)
<re.Match object; span=(0, 7), match='morning'>
>>> pattern.search(string)
<re.Match object; span=(0, 7), match='morning'>
>>> pattern.findall(string)
['morning', 'morning', 'morning']
>>> [match for match in pattern.finditer(string)]
[<re.Match object; span=(0, 7), match='morning'>, <re.Match object; span=(8, 15), match='morning'>, <re.Match object; span=(16, 23), match='morning'>]