请解释正则表达式中的 `^` 和 `$` 的作用,并说明它们在多行模式下的行为有何不同?

正则表达式中的 ^ 和 $ 是两个非常重要的元字符,用于匹配字符串的边界。以下是它们的详细作用和在不同模式下的行为差异。

1. ^ 的作用

^ 表示匹配字符串的开头。在多行模式下,它还可以匹配每一行的开头。

示例 1:匹配字符串的开头

import re

# 匹配以 "Hello" 开头的字符串
pattern = r'^Hello'
result = re.match(pattern, "Hello world")
print(result.group())  # 输出: Hello

示例 2:多行模式下匹配每行的开头

import re

# 多行模式下匹配每行的开头
text = "Hello\nworld\nPython"
pattern = r'^\w+'
result = re.findall(pattern, text, flags=re.MULTILINE)
print(result)  # 输出: ['Hello', 'world', 'Python']

2. $ 的作用

$ 表示匹配字符串的结尾。在多行模式下,它还可以匹配每一行的结尾。

示例 1:匹配字符串的结尾

import re

# 匹配以 "world" 结尾的字符串
pattern = r'world$'
result = re.search(pattern, "Hello world")
print(result.group())  # 输出: world

示例 2:多行模式下匹配每行的结尾

import re

# 多行模式下匹配每行的结尾
text = "Hello\nworld\nPython"
pattern = r'\w+$'
result = re.findall(pattern, text, flags=re.MULTILINE)
print(result)  # 输出: ['Hello', 'world', 'Python']

3. 单行模式 vs. 多行模式

  • 单行模式(默认):^ 和 $ 分别匹配整个字符串的开头和结尾,不会考虑字符串内部的换行符。
  • 多行模式(re.MULTILINE):^ 和 $ 会分别匹配每一行的开头和结尾,从而可以逐个处理多行文本中的内容。

对比示例

import re

# 多行文本
text = "Hello\nworld\nPython"

# 单行模式(默认)
pattern1 = r'^\w+'
result1 = re.findall(pattern1, text)
print("单行模式:", result1)  # 输出: ['Hello'](只匹配整个字符串的开头)

# 多行模式
pattern2 = r'^\w+'
result2 = re.findall(pattern2, text, flags=re.MULTILINE)
print("多行模式:", result2)  # 输出: ['Hello', 'world', 'Python'](匹配每行的开头)

4. 总结

  • ^ 和 $ 在单行模式下仅匹配字符串的开头和结尾。
  • 在多行模式下,它们会分别匹配每一行的开头和结尾,使得正则表达式能够逐行处理文本内容。
  • 通过 re.MULTILINE 标志可以启用多行模式,从而灵活处理多行文本。

通过上述示例和解释,可以清晰地理解 ^ 和 $ 的作用及其在不同模式下的行为差异。