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

如何按规则从多行文本文件提取指定字符串(含修正需求)

正确提取指定字符串的实现方案

需求回顾

  • 从多行文本的{}块中提取三个目标字段:String server、pac、String method,每个块内每个字段最多出现1次
  • String server仅提取被双引号/单引号包裹的值,且需去除值中的()符号
  • pac字段的值优先级高于String server,即同一块内同时存在时,优先取pac的值
  • 服务器/pac值必须出现在String method值之前才有效,且每个块内仅保留一个有效服务器/pac值

测试文本示例

{
    String server = "example.com()";
    String method = "callA";
}
{
    pac = "proxy.example.net";
    String method = "callB";
}
{
    String server = unquotedValue; // 忽略此server值
    String method = "callC";
}
{
    String method = "determineI";
    String server = "lateServer()"; // server在method之后,忽略
}
{
    pac = "proxyIIIII";
    String method = "callI";
}

预期输出

  • example.com, callA
  • proxy.example.net, callB
  • , callC
  • , determineI
  • proxyIIIII, callI

实现方案(Python)

使用正则表达式结合块遍历,确保字段顺序和优先级逻辑正确:

import re

def extract_entries(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 分割所有{}块(假设无嵌套块)
    blocks = re.findall(r'\{(.*?)\}', content, re.DOTALL)
    results = []
    
    for block in blocks:
        # 优先匹配pac值
        pac_match = re.search(r'\bpac\s*=\s*["\']([^"\']+)["\']', block)
        server_value = None
        if pac_match:
            server_value = pac_match.group(1)
        else:
            # 匹配被引号包裹的String server值
            server_match = re.search(r'String\s+server\s*=\s*["\']([^"\']+)["\']', block)
            if server_match:
                # 去除值中的()符号
                server_value = re.sub(r'\(|\)', '', server_match.group(1))
        
        # 匹配String method值
        method_match = re.search(r'String\s+method\s*=\s*["\']([^"\']+)["\']', block)
        method_value = method_match.group(1) if method_match else None
        
        # 校验服务器/pac值是否在method之前出现
        if method_match and server_value is not None:
            target_pos = block.find(pac_match.group(0) if pac_match else server_match.group(0))
            method_pos = block.find(method_match.group(0))
            if target_pos > method_pos:
                server_value = None
        
        # 组装结果条目
        server_part = server_value if server_value is not None else ''
        method_part = method_value if method_value is not None else ''
        results.append(f"{server_part}, {method_part}")
    
    return results

# 调用示例
for entry in extract_entries('your_file.txt'):
    print(entry)

方案说明

  1. 块分割:用re.DOTALL模式匹配多行{}块,确保每个块内的内容被完整捕获
  2. 优先级处理:先匹配pac字段,存在则直接使用;不存在再匹配符合引号要求的String server
  3. 顺序验证:通过字符位置比较,确保服务器/pac字段出现在method字段之前,否则忽略该值
  4. 值清洗:对String server的提取值自动去除()符号,保留引号内的有效内容

原方案问题分析

原方案大概率未处理字段顺序校验,导致determineI块中server在method之后仍被错误提取;或未正确实现pac字段的优先级匹配逻辑,导致IIIII callI块的pac值未被正确捕获。本方案通过位置校验和优先级前置匹配解决了这些问题。

内容的提问来源于stack exchange,提问作者albertkao9

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:16:19