liveBook · Manning

Re.search

As explained in The Quick Python Book, Fourth Edition

search is a regular-expression pattern method that looks for the first match of a pattern within a string and returns a match object or None.

Use `search` to look for the first occurrence of a regular-expression pattern in a string. A compiled pattern’s `search` method returns `None` when it finds no match. Otherwise, it returns a match object, which is true in a Boolean test and can provide information about the matched text. section 16.1

Check whether a line contains a word

`import re; pattern = re.compile("hello")`. Then `if pattern.search(line):` runs its body only when the line contains `hello`. Compile the pattern once when searching many lines; compilation can significantly speed up large text-processing jobs. section 16.1

import re
regexp = re.compile("hello")
count = 0
file = open("textfile", 'r')
for line in file.readlines():
   if regexp.search(line):
       count = count + 1
file.close()
print(count)

This listing searches each line of a file and counts matching lines. The Boolean test uses the match object without extracting text from it. section 16.1

Keep the result when you need data from the match: `result = pattern.search(line)`. Check that `result` is not `None` before calling `result.group('phone')` or another named group. A successful overall match does not guarantee text for every group: an optional middle-name group can still return `None`. section 16.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through compiled-pattern searches and match-object extraction, but leaves advanced search controls to documentation.
Examples
Counts file lines containing `hello` and extracts names and phone numbers from matching records.
What it assumes
Assumes familiarity with Python strings, imports, conditionals, and loops while introducing regex compilation and match results.
What you can do after
Apply it via Python’s `re` module to test strings and retrieve named fields from successful matches.
How it connects
Connects `re.compile`, match objects, named groups, optional subpatterns, and raw strings.

Also explained in

Compare how 2 books explain re.search →

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.