1. Search
A regular expression (regex) is a text pattern used to find parts of a string. Python's re module is part of the standard library:
re.search() is a function with this signature:
pattern— the regex to look for, written as a string.string— the text to scan.flags— optional;0means no special options (the ignore-case lesson covers them).- It returns a match object for the first occurrence, or
Nonewhen nothing matches.
A match object tells you what matched and where:
.group()— the matched text..start()— index of the first matched character, counted from0..end()— index after the last matched character, so the match isstring[start:end]..span()— the tuple(start, end).
None is falsy, so if match: is the usual way to check whether something was found. re.search() stops at the first match and ignores the rest.
Coming from JavaScript? re.search(pattern, text) is close to text.match(pattern) for the first match, but Python returns a match object or None instead of null, and .group() replaces match[0].
Find a word
Import re and call re.search() with the pattern "mundo" and the text "Hola mundo". Store the result in a variable and print its .group().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Search without a match
Search for "Python" in "Hola mundo". When nothing matches, re.search() returns None. Print the result of the search directly.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read the positions
Search for "IA" in "Todo el mundo habla de IA". Print .start() on one line and .end() on the next.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Search stops at the first match
Search for "IA" in "We use IA. IA is risky.". re.search() returns only the first occurrence. Print the matched text and its start index on the same line, separated by a space.
Print exactly:
Create a free account to save your progress and unlock chapter 2.