Python Regex

Python provides a built-in module called re (regular expression) that allows you to work with regular expressions. Here are some basic examples of using regular expressions in Python:

  1. Matching a string:
  2. import re
    
    string = "Hello, World!"
    pattern = "Hello"
    match = re.search(pattern, string)
    if match:
        print("Match found!")
    else:
        print("Match not found.")
    

    This will output “Match found!” because the pattern “Hello” matches the string “Hello, World!”.

    1. Finding all occurrences of a pattern in a string:
import re

string = "The quick brown fox jumps over the lazy dog."
pattern = "the"
matches = re.findall(pattern, string, re.IGNORECASE)
print(matches)

This will output [“the”, “the”] because there are two occurrences of the pattern “the” in the string. The re.IGNORECASE flag makes the search case-insensitive.

  1. Replacing a pattern in a string:
import re

string = "Hello, World!"
pattern = "Hello"
replacement = "Hi"
new_string = re.sub(pattern, replacement, string)
print(new_string)

This will output “Hi, World!” because the pattern “Hello” is replaced with “Hi” in the string.

These are just a few examples of what you can do with regular expressions in Python. The re module provides many more functions and options for working with regular expressions.

Matching Versus Searching:

In regular expressions, there are two main functions for finding patterns in a string: matching and searching.

Matching is used to check if the entire string matches a certain pattern. For example, if you want to check if a string contains only alphanumeric characters, you can use the following code:

import re

string = "Hello123"
pattern = "^[a-zA-Z0-9]+$"
match = re.match(pattern, string)
if match:
    print("Match found!")
else:
    print("Match not found.")

This will output “Match found!” because the string “Hello123” matches the pattern ^[a-zA-Z0-9]+$.

Searching, on the other hand, is used to find the first occurrence of a pattern in a string. For example, if you want to find the first occurrence of the word “world” in a string, you can use the following code:

import re

string = "Hello, world!"
pattern = "world"
match = re.search(pattern, string)
if match:
    print("Match found!")
else:
    print("Match not found.")

This will output “Match found!” because the pattern “world” is found in the string “Hello, world!”.

In general, if you want to check if a string matches a certain pattern exactly, use re.match(). If you want to find the first occurrence of a pattern in a string, use re.search(). However, both functions can be useful depending on your specific use case.