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

如何拆分两种不同字符串提取对应前缀编码得到指定格式输出

字符串拆分提取解决方案

核心逻辑

  • 两个场景符合共通规则:所有需要提取的内容,都位于每个条目固定分隔符-(空格+连字符+空格)的前侧
  • 无需提前按逗号拆分条目,直接通过正则匹配所有符合规则的片段即可,自动规避描述内容中嵌套的逗号干扰
  • 提取匹配结果后去除每个片段的前后空格,再按需求拼接得到最终输出

代码实现(Python示例)

import re

def extract_target_content(input_str: str) -> str:
    # 正则匹配所有` - `前的有效前缀:前缀开头为大写字母或数字,可包含数字、字母、空格、点
    pattern = r'([A-Z0-9][A-Z0-9\s.]*?) -'
    match_result = re.findall(pattern, input_str)
    # 去除每个匹配项前后空格后拼接
    final_output = ', '.join([item.strip() for item in match_result])
    return f'"{final_output}"'

# 场景1测试
scene1_input = "\"12.2 - Chemicals, products and including,14.0 - Plastic products ,17.2 - Metal Products ,19.1 - and optical equipment (excluding and other electronic components; semiconductors; bare printed circuit boards; opti, watches)\""
print(extract_target_content(scene1_input))
# 输出符合预期:"12.2, 14.0, 17.2, 19.1"

# 场景2测试
scene2_input = "\"MD 0102.2.3 - Test 123 ,MD 0102.2.5 - Test Hello ,MD 1101.2 - Dialysis and blood treatment, MDM 123 - Test, MDM 12.32.0 - Test 12\""
print(extract_target_content(scene2_input))
# 输出符合预期:"MD 0102.2.3, MD 0102.2.5, MD 1101.2, MDM 123, MDM 12.32.0"

如果需要调整拼接后逗号前后的空格规则,修改join方法内的拼接字符即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:54:05