[941] re module in Python

发布时间 2023-11-17 06:27:19作者: McDelfino

The re module in Python is used for regular expressions. It provides a set of functions that allows us to search a string for a match, replace substrings, and more, using regular expressions. Here's a basic guide on how to use the re module:

1. Import the re module:

import re

2. Basic Patterns and Functions:

a. re.search(pattern, string):

Search for a pattern in a string. Returns a match object if found, None otherwise.

- My view: it only returns the first match object.

pattern = r"apple"
string = "I love apples"

match = re.search(pattern, string)

if match:
    print("Pattern found:", match.group())
else:
    print("Pattern not found")

b. re.match(pattern, string):

Check if the pattern matches at the beginning of the string.

- My view: it only matches from the beginning and the only one.

pattern = r"Hello"
string = "Hello, world!"

match = re.match(pattern, string)

if match:
    print("Pattern found at the beginning:", match.group())
else:
    print("Pattern not found at the beginning")

c. re.findall(pattern, string):

Find all occurrences of a pattern in a string.

- My view: it will return all the match objects.

pattern = r"\d+"  # Match one or more digits
string = "There are 123 apples and 456 oranges."

matches = re.findall(pattern, string)
print("Matches:", matches)

3. Regular Expression Patterns:

  • \d: Matches any digit (0-9).
  • \w: Matches any alphanumeric character (equivalent to [a-zA-Z0-9_]).
  • .: Matches any character except a newline.
  • *: Matches 0 or more occurrences of the preceding character.
  • +: Matches 1 or more occurrences of the preceding character.
  • ?: Matches 0 or 1 occurrence of the preceding character.
  • ^: Anchors the match at the beginning of the string.
  • $: Anchors the match at the end of the string.

4. Groups and Capturing:

pattern = r"(\d+)-(\w+)"
string = "123-apple"

match = re.search(pattern, string)

if match:
    print("Full match:", match.group(0))
    print("Number:", match.group(1))
    print("Fruit:", match.group(2))

These are just some basics to get you started. Regular expressions can get quite complex, and you can create more sophisticated patterns for different matching scenarios. The re module provides various functions and flags for customization, so refer to the official documentation for more details.