【Python 学习笔记】regex basic

how to write regex pattern in python?

In Python, you can write and use regular expressions (regex) using the re module. Here’s a basic overview of how to write and use regex patterns in Python.

Steps to Write a Regex Pattern:

  1. Import the re module: This module provides all the regex-related functionality.
  2. Define a regex pattern: Regex patterns are written as raw strings (prefixed with r"pattern") to avoid Python treating backslashes (\) as escape characters.
  3. Use the regex functions: Functions like re.search(), re.match(), re.findall(), re.sub(), and others can be used to apply the pattern to a string.

Basic Syntax for Writing a Regex Pattern:

  • Literal Characters: Match the characters as they appear (e.g., r"abc").
  • Metacharacters: Special characters like . (any character), \d (digit), \w (word character), \s (whitespace), etc.
  • Quantifiers: Specify how many times a character/group should occur. E.g., * (0 or more), + (1 or more), {n} (exactly n times), etc.
  • Anchors: Mark positions in the string. E.g., ^ (start of string), $ (end of string).

Example of Groups and Backreferences using re.search()

# Using groups to capture parts of a pattern
pattern = r"(\d{3})-(\d{2})-(\d{4})"
text = "SSN: 123-45-6789"

match = re.search(pattern, text)
if match:
    print(match.group(1))  # Output: 123
    print(match.group(2))  # Output: 45
    print(match.group(3))  # Output: 6789

Example of using re.findall():

# Finding all occurrences of a pattern
text = "My phone number is 123-456-7890, and my office number is 098-765-4321."
pattern = r"\d{3}-\d{3}-\d{4}"  # Matches phone numbers

matches = re.findall(pattern, text)
print(matches)  # Output: ['123-456-7890', '098-765-4321']

Example of using re.sub():

# Replacing digits with asterisks
text = "My password is 12345."
pattern = r"\d"

# Replace each digit with '*'
masked_text = re.sub(pattern, "*", text)
print(masked_text)  # Output: My password is *****.

re.match()

  • re.match() checks if the pattern matches at the start of the string.
  • If there is no match at the beginning, None is returned.
  • Use match.group() to extract the matched string if a match is found.
  • Can be replaced with re.search() by anchoring the pattern to the start of the string using the ^ (caret) metacharacter.

Special Characters -  see CSDN

Answer Generated by OpenAI's ChatGPT"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值