Level 1
0 / 100 XP

Importing Regex and manipulating strings

Welcome to the tutorial on "Employing Regex and Shaping Strings"! We're about to dive into the world of regular expressions (Regex) in Python, taking a journey through the re module and its many utilities. The re module is a toolbox for everything from pattern matching to string division, and all it takes to unlock these tools is a simple import statement. Let's get started!

Kick off by drawing the re module into your Python script:

import re

Having brought in the re module, a myriad of Regex functions is now at your fingertips. Let's inspect some of the key functions:

re.match(pattern, string): Examines whether the pattern is present at the outset of the string. It offers a match object for a successful match, or None otherwise. For instance:

Python
import re pattern = r"Hello" string = "Hello, World!" match = re.match(pattern, string) if match: print("Pattern matched!") else: print("No match found.")

In the above snippet, r"Hello" is pitted against "Hello, World!". A successful match at the string's start triggers the "Pattern matched!" message.

re.search(pattern, string): Hunts for the pattern's initial appearance within the string, returning a match object for a hit or None otherwise. As an example:

match = re.search(pattern, string)

Here, r"World" is sought in "Hello, World!". The pattern's presence prompts the "Pattern found!" message.

re.findall(pattern, string): Retrieves all instances of the pattern within the string, returning them in a list. For example:

Python
import re pattern = r"\\d+" string = "I have 3 apples and 5 oranges." matches = re.findall(pattern, string) print(matches)

The snippet uses r"\d+" to detect one or more digit characters in "I have 3 apples and 5 oranges.". With re.findall(), the result is ['3', '5'] - the discovered matches.

re.sub(pattern, repl, string): Sw…