Camkode
Camkode

How to Use Python's Regular Expressions (Regex)

Posted by Kosal

How to Use Python's Regular Expressions (Regex)

Using regular expressions (regex) in Python involves using the re module, which provides support for working with regular expressions. Here's a basic overview of how to use regex in Python:

1. Import the re module:

import re

2. Compile a regular expression pattern:

pattern = re.compile(r'your_regex_pattern_here')

3. Use the regex functions provided by the re module:

3.1. Match:

result = pattern.match(string)

This checks if the regex pattern matches at the beginning of the string.

result = pattern.search(string)

This searches the entire string for a match.

3.3. Find all:

results = pattern.findall(string)

This finds all occurrences of the pattern in the string and returns them as a list.

3.4. Substitution:

new_string = pattern.sub(replacement, string)

This replaces occurrences of the pattern in the string with the replacement.

Example:

import re

# Define a regex pattern
pattern = re.compile(r'\b\w{4}\b')

# Sample string
string = "This is a sample text with some words."

# Find all 4-letter words in the string
results = pattern.findall(string)

# Print the results
print(results)  # Output: ['This', 'text', 'with', 'some']

Additional Notes:

  • \b represents a word boundary.
  • \w matches any word character (equivalent to [a-zA-Z0-9_]).
  • {4} matches the previous token exactly 4 times.

Regular expressions can be complex and powerful, so it's recommended to refer to the Python documentation or other resources for more advanced usage and syntax. Additionally, websites like regex101.com can be helpful for testing and visualizing regular expressions.