在正则表达式中,可以使用圆括号来指定一个子表达式。子表达式可以用于分组、捕获和引用。
要获取括号里的内容,可以使用捕获组。捕获组是由括号内的表达式定义的,可以通过捕获组的索引或名称来引用它们的内容。
以下是一些示例:
- 使用括号捕获整个字符串:
import re pattern = r"(.*?)" text = "Hello, World!" match = re.search(pattern, text) if match: content = match.group(1) print(content) # 输出: Hello, World!
- 使用括号捕获特定部分的内容:
import re pattern = r"Hello, (.*?)!" text = "Hello, World!" match = re.search(pattern, text) if match: content = match.group(1) print(content) # 输出: World
- 使用命名捕获组:
import re pattern = r"Hello, (?P.*?)!" text = "Hello, World!" match = re.search(pattern, text) if match: content = match.group("name") print(content) # 输出: World
注意,在使用捕获组时,可以通过group()
方法来获取捕获组的内容,括号内可以指定捕获组的索引或名称。索引从1开始,0代表整个匹配的内容。
以上是一些基本的示例,根据实际情况可以进行更复杂的正则表达式匹配和捕获。