You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.12:如何提取group()/not group()内的目标子字符串?

提取group()/not group()内子字符串的解决方案

需求:使用Python 3.12从文本行中提取group()或not group()括号内的内容,示例行如下:

line1: 'group(something)'
line2: 'other(something) and group(something,something,something) and not group(something,something)'

原自定义函数find_within仅能处理单组括号场景,在多括号行中会失效:

  • 使用find()匹配右括号时,会命中第一个)导致提取内容为空
  • 换成rfind()则会匹配最后一个),提取大量无关内容

以下是两种可行的解决方案:

一、正则表达式(推荐)

正则能精准定位对应group(/not group(的闭合括号,代码实现如下:

import re

def extract_group_content(line):
    # 匹配 group(...) 或 not group(...) 内的内容
    pattern = r'(?:not )?group\((.*?)\)'
    # 获取所有匹配的括号内内容
    return re.findall(pattern, line)

# 测试
line1 = 'group(something)'
line2 = 'other(something) and group(something,something,something) and not group(something,something)'

print(extract_group_content(line1))  # 输出: ['something']
print(extract_group_content(line2))  # 输出: ['something,something,something', 'something,something']

正则说明

  • (?:not )?:匹配可选的not 前缀,非捕获组避免将not纳入结果
  • group\(:匹配字面量group(
  • (.*?):非贪婪匹配任意字符,直到遇到当前group()对应的第一个),确保提取内容精准

二、手动计数括号改进函数

若不想使用正则,可通过遍历字符串并计数括号来定位对应闭合括号:

def find_within(search_in, search_for, until_char):
    start_idx = search_in.find(search_for)
    if start_idx == -1:
        return ""
    
    current_pos = start_idx + len(search_for)
    bracket_count = 0
    
    while current_pos < len(search_in):
        char = search_in[current_pos]
        if char == until_char:
            if bracket_count == 0:
                return search_in[start_idx + len(search_for) : current_pos]
            bracket_count -= 1
        elif char == '(':
            bracket_count += 1
        current_pos += 1
    return ""

# 测试
line2 = 'other(something) and group(something,something,something) and not group(something,something)'
group2 = find_within(line2, 'and group(', ')')
not_group = find_within(line2, 'not group(', ')')

print(group2)  # 输出: 'something,something,something'
print(not_group)  # 输出: 'something,something'

逻辑说明

从search_for结束位置开始遍历,遇到(则计数+1,遇到)则计数-1,当计数归0时的)就是目标闭合括号,支持处理嵌套括号场景。


内容的提问来源于stack exchange,提问作者S'mon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:14:58