Regular Expression
Chapter 4
Why use RegEx
What are regular expressions
Python RegEx
• A RegEx, or Regular Expression, is a sequence of characters that forms
a search pattern.
• RegEx can be used to check if a string contains the specified search
pattern.
• RegEx Module
• Python has a built-in package called re, which can be used to work
with Regular Expressions.
• Import the re module:
import re
Module Contents
• The module defines several functions, constants, and an exception.
Some of the functions are simplified versions of the full featured
methods for compiled regular expressions. Most non-trivial
applications always use the compiled form.
• See documentation:
• https://docs.python.org/3/library/re.html
• https://www.w3schools.com/python/python_regex.asp
• re.compile(pattern, flags=0)
• Compile a regular expression pattern into a regular expression object,
• prog = re.compile(pattern)
• result = prog.match(string)
• is equivalent to
• result = re.match(pattern, string)
• but using re.compile() and saving the resulting regular expression
object for reuse is more efficient when the expression will be used
several times in a single program.
• re.search(pattern, string, flags=0)
• Scan through string looking for the first location where the regular
expression pattern produces a match, and return a corresponding
match object. Return None if no position in the string matches the
pattern; note that this is different from finding a zero-length match at
some point in the string.