当前位置:   article > 正文

【Python入门与进阶】Python 中的正则表达式

【Python入门与进阶】Python 中的正则表达式

Python 中的正则表达式是通过内置模块 re 来实现的。正则表达式是一种用于模式匹配和文本处理的强大工具,可以用于查找、替换、分割字符串等操作。

基本用法

以下是 re 模块中一些常用的函数和方法:

  1. re.compile(pattern, flags=0):编译正则表达式模式,返回一个模式对象。
  2. re.search(pattern, string, flags=0):在整个字符串中搜索模式,返回第一个匹配对象。
  3. re.match(pattern, string, flags=0):从字符串的起始位置开始匹配模式,返回匹配对象。
  4. re.findall(pattern, string, flags=0):返回字符串中所有非重叠匹配的列表。
  5. re.finditer(pattern, string, flags=0):返回字符串中所有非重叠匹配的迭代器。
  6. re.sub(pattern, repl, string, count=0, flags=0):替换字符串中所有匹配模式的子串。
  7. re.split(pattern, string, maxsplit=0, flags=0):使用模式分割字符串,返回分割后的列表。

示例代码

以下是一些示例代码,展示了如何使用上述函数:

import re

# 定义一个正则表达式模式
pattern = r'\d+'  # 匹配一个或多个数字

# 在字符串中搜索
string = "The price is 100 dollars and 50 cents"
match = re.search(pattern, string)
if match:
    print(f"Found: {match.group()}")  # 输出: Found: 100

# 从字符串起始位置开始匹配
match = re.match(pattern, string)
if match:
    print(f"Match from start: {match.group()}")
else:
    print("No match from start")  # 输出: No match from start

# 查找所有匹配项
matches = re.findall(pattern, string)
print(f"All matches: {matches}")  # 输出: All matches: ['100', '50']

# 迭代匹配项
for match in re.finditer(pattern, string):
    print(f"Iter match: {match.group()}")  # 输出: Iter match: 100, Iter match: 50

# 替换匹配项
replaced_string = re.sub(pattern, '#', string)
print(f"Replaced string: {replaced_string}")  # 输出: Replaced string: The price is # dollars and # cents

# 分割字符串
split_string = re.split(r'\s+', string)  # 按空白字符分割
print(f"Split string: {split_string}")  # 输出: Split string: ['The', 'price', 'is', '100', 'dollars', 'and', '50', 'cents']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

正则表达式语法

正则表达式的语法非常丰富,以下是一些常用的语法元素:

  • .:匹配任意单个字符(除换行符)。
  • ^:匹配字符串的开始。
  • $:匹配字符串的结束。
  • *:匹配前一个字符零次或多次。
  • +:匹配前一个字符一次或多次。
  • ?:匹配前一个字符零次或一次。
  • {n}:匹配前一个字符恰好 n 次。
  • {n,}:匹配前一个字符至少 n 次。
  • {n,m}:匹配前一个字符至少 n 次,但是不超过 m 次。
  • []:匹配括号内的任意一个字符,例如 [abc] 匹配 abc
  • |:匹配左边或右边的表达式,例如 a|b 匹配 ab
  • ():捕获组,用于提取匹配的子串。

转义字符

有些字符在正则表达式中有特殊含义,如果你想匹配它们的字面意思,需要使用转义字符 \,例如:

  • \.:匹配字符 .
  • \\:匹配字符 \

模式修饰符

re 模块支持一些修饰符,用于改变正则表达式的行为:

  • re.IGNORECASE (re.I):忽略大小写。
  • re.MULTILINE (re.M):多行模式,^$ 匹配每一行的开始和结束。
  • re.DOTALL (re.S):让 . 匹配所有字符,包括换行符。
  • re.VERBOSE (re.X):忽略模式中的空白符和注释,以便提高可读性。
pattern = re.compile(r"""
    \d+     # 匹配一个或多个数字
    \s+     # 匹配一个或多个空白字符
    \w+     # 匹配一个或多个字母数字字符
""", re.VERBOSE)
  • 1
  • 2
  • 3
  • 4
  • 5

掌握正则表达式可以大大提高处理字符串的效率和灵活性。

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号