liveBook · Manning

Re

As explained in The Quick Python Book, Fourth Edition

re is Python's standard-library module for matching and processing text with regular expressions.

re is Python’s standard-library module for recognizing, extracting, searching, and replacing text that fits regular-expression patterns. It provides a more flexible alternative to simple substring methods. section 3.2.4 section 16.7

Core ideas include:

  • A regular expression is a pattern string whose metacharacters can match many specific strings. section 16.1
  • re.compile(pattern) creates a compiled regular expression; compilation is optional but can improve performance when processing large amounts of text. section 16.1
  • search(text) returns a match object when the pattern occurs and None when it does not. section 16.1
  • sub(replacement, text) replaces matching portions, while other methods support splitting, extraction, position lookup, and controlled iteration. section 16.7
  • Prefixing a pattern string with r makes it a raw string, so Python does not process its escape sequences first. section 16.7

Normalize irregular whitespace

import re x = "live and let \t \tlive" pattern = re.compile(r"[\t ]+") pattern.sub(" ", x) # 'live and let live' section 3.2.4

Count matching lines

regexp = re.compile("hello") count = 0 for line in file.readlines(): if regexp.search(line): count += 1 # search detects whether each line contains the pattern section 16.1

x = "live and     let \t   \tlive"
x.split()
 
['live', 'and', 'let', 'live']
 
x.replace("    let \t   \tlive", "enjoy life")
 
'live and enjoy life'
 
import re                               #1
regexpr = re.compile(r»[\t ]+»)
regexpr.sub(" ", x)
 
'live and let live'
#1 re module used to replace all spaces

Compare ordinary splitting and replacement with a compiled regular expression that collapses mixed spaces and tabs. section 3.2.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains patterns, compilation, search results, raw strings, replacements, flags, and match processing without detailing every special character.
Examples
Uses whitespace normalization and line counting for text containing the word hello.
What it assumes
Assumes general Python and string knowledge while introducing regular-expression patterns, compilation, and match detection through examples.
What you can do after
Apply re.compile, search, and sub to detect patterns, inspect matches, count matching lines, and normalize text.
How it connects
Connects regular expressions with string searching, string replacement, raw strings, match objects, regex flags, and substring methods.

Also explained in

Compare how 2 books explain re →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.