Python Regular Expressions (Regex) Tutorial 🎯

beginner
14 min

Python Regular Expressions (Regex) Tutorial 🎯

Welcome to our in-depth Python Regex tutorial! Today, we'll learn about regular expressions, a powerful tool for pattern matching that can greatly enhance your text processing skills. 📝

Regular expressions, often abbreviated as regex or regexp, are a sequence of characters that form a search pattern. They are used to search, replace, or manipulate text based on specific patterns. Let's dive into the world of regex!

Understanding Regex 💡

Regular expressions are like a search-and-replace superpower for your code. They allow you to find and manipulate specific patterns in strings easily.

In Python, we use the re module to work with regular expressions. Let's see how to import and use this module.

python
import re # Creating a pattern pattern = re.compile(r'example') # Searching for the pattern in a string match = pattern.search('This is an example string.') # Check if the pattern was found if match: print('Pattern found!') else: print('Pattern not found.')

In the code above, we import the re module, create a pattern, and use it to search for the word 'example' in a string.

Basic Regex Types and Syntax 📝

Regex consists of different types and characters to create complex search patterns. Here are some basic ones:

  • Dot (.): Matches any character except a newline
  • Square brackets []: Matches a single character from a set
  • Caret ^: Matches the start of a line
  • Dollar sign $: Matches the end of a line
  • Asterisk *: Matches zero or more occurrences of the preceding character
  • Plus sign +: Matches one or more occurrences of the preceding character
  • Question mark ?: Matches zero or one occurrence of the preceding character
  • Pipe |: Matches either of the patterns separated by the pipe

Let's see some examples:

python
import re # Match any 5-letter word pattern = re.compile(r'\b\w{5}\b') # Test the pattern on a string string = 'This is a sample string.' matches = pattern.findall(string) print(matches)

In this example, we match any 5-letter word (assuming 'word' is 5 letters long). The \b characters ensure we match words (not parts of words).

Regex in Action: Practice Quiz 🎯

Now, let's test your understanding of basic regex concepts!

Quick Quiz
Question 1 of 1

What does the '.' character represent in a regular expression?

Capturing Groups and Substitutions 💡

Capturing groups allow us to extract specific parts of a matched pattern. In Python, we can use parentheses () to create groups.

Let's see an example where we extract the numbers from a string:

python
import re # Match and capture numbers pattern = re.compile(r'\b\d+\b') # Test the pattern on a string string = 'This string contains the numbers: 123, 456, 789' matches = pattern.findall(string) print(matches)

In this example, we match and capture any sequence of digits.

We can also use substitutions to replace matched patterns. The substitution syntax is:

python
re.sub(pattern, replacement, string, count=0, flags=0)

Here, pattern is the pattern to search, replacement is the text to replace the matches with, and string is the string to search in.

Let's replace all the numbers in a string with their squares:

python
import re # Replace numbers with their squares pattern = re.compile(r'\b\d+\b') replacement = r'{\1}²' # Test the pattern on a string string = 'This string contains the numbers: 1 2 3 4 5' result = re.sub(pattern, replacement, string) print(result)

In this example, we replace each number with its square, enclosed in curly braces {}. The \1 inside the replacement string refers to the first captured group (the number that was matched).

Advanced Regex and Practical Examples 💡

In this section, we'll learn about more advanced regex concepts and see how to use them in practical examples.

  • Character classes []: Match a single character from a set
  • Ranges []: Match a range of characters
  • Negated character classes [^]: Match any character not in the set
  • Verbatim string r: Prevents backslashes from being interpreted as escape characters
  • **Escape sequence **: Escape special characters
  • Backreferences \n: References to previously captured groups
  • Lookahead assertions (?=): Match a pattern if it is followed by another pattern
  • Lookbehind assertions (?<=): Match a pattern if it is preceded by another pattern

Let's see some examples:

python
import re # Match email addresses pattern = re.compile(r'[\w.]+@[\w.]+\.[\w.]+') # Test the pattern on a string string = 'john.doe@example.com, jane_doe@another-example.com' matches = pattern.findall(string) print(matches)

In this example, we match email addresses using character classes, ranges, and verbatim strings.

Wrapping Up 📝

Congratulations on reaching the end of this comprehensive Python Regex tutorial! Regular expressions are a powerful tool for text processing and can greatly enhance your programming skills. Practice is key, so don't forget to test your understanding with the provided quiz and try out more regex examples in your own projects. Happy coding! 🚀