插件窝 干货文章 Python正则表达式匹配括号:为何findall()有时会丢掉括号?

Python正则表达式匹配括号:为何findall()有时会丢掉括号?

括号 捕获 使用 findall 103    来源:    2025-03-14

在Python中,使用正则表达式时,re.findall() 函数的行为有时会让人感到困惑,尤其是在处理带有括号的匹配时。findall() 函数的行为取决于正则表达式中是否使用了捕获组(即括号 ())。

1. 不使用捕获组的情况

如果正则表达式中没有使用捕获组(即没有使用括号 ()),findall() 会返回所有匹配的完整字符串。

例如:

import re

text = "This is a (test) string with (multiple) parentheses."
pattern = r'\(.*?\)'  # 匹配括号及其内容

matches = re.findall(pattern, text)
print(matches)

输出:

['(test)', '(multiple)']

在这个例子中,findall() 返回了所有匹配的完整字符串,包括括号。

2. 使用捕获组的情况

如果正则表达式中使用了捕获组(即使用了括号 ()),findall() 会返回捕获组中的内容,而不是整个匹配的字符串。

例如:

import re

text = "This is a (test) string with (multiple) parentheses."
pattern = r'\((.*?)\)'  # 匹配括号内的内容

matches = re.findall(pattern, text)
print(matches)

输出:

['test', 'multiple']

在这个例子中,findall() 只返回了括号内的内容,而括号本身被丢弃了。

3. 如何保留括号

如果你希望保留括号,但又需要使用捕获组,可以在正则表达式中使用非捕获组 (?:...)。非捕获组不会影响 findall() 的返回结果。

例如:

import re

text = "This is a (test) string with (multiple) parentheses."
pattern = r'\((?:.*?)\)'  # 使用非捕获组

matches = re.findall(pattern, text)
print(matches)

输出:

['(test)', '(multiple)']

在这个例子中,findall() 返回了完整的匹配字符串,包括括号。

4. 总结

  • 如果正则表达式中没有使用捕获组,findall() 会返回所有匹配的完整字符串。
  • 如果正则表达式中使用了捕获组,findall() 会返回捕获组中的内容,而不是整个匹配的字符串。
  • 如果你希望保留括号但又需要使用捕获组,可以使用非捕获组 (?:...)

希望这个解释能帮助你理解 findall() 的行为,并在处理括号时避免不必要的困惑。