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

如何用正则表达式(Regex)提取特定短横线间的目标数据?

正则提取解决方案

需求回顾

给定字符串格式为 Prefix/Product-[1stMod-]SubProduct-2ndMod-Patch,需要提取两组内容:

  • 第一组:第一个短横线与倒数第二个短横线之间的内容([1stMod-]SubProduct,其中1stMod-可选)
  • 第二组:倒数第二个短横线至字符串末尾的内容(2ndMod-Patch,其中2ndMod-必存在)

正则表达式

^.*?-([\s\S]*)-([^-]+-[^-]+)$

表达式解释

  • ^.*?-:匹配字符串开头到第一个短横线(非贪婪匹配确保仅匹配到首个短横线)
  • ([\s\S]*):捕获第一组内容,[\s\S]覆盖任意字符(含换行),匹配从首个短横线后到倒数第二个短横线前的所有内容
  • -:匹配倒数第二个短横线
  • ([^-]+-[^-]+):捕获第二组内容,强制匹配xxx-xxx格式(符合2ndMod-Patch的结构要求,保证2ndMod-必存在)
  • $:匹配字符串结尾

代码示例(Python)

import re

# 定义正则模式
pattern = r'^.*?-([\s\S]*)-([^-]+-[^-]+)$'

# 测试用例
test_cases = [
    'Prefix/Product-SubProduct-2ndMod-Patch',
    'Prefix/Product-1stMod-SubProduct-2ndMod-Patch'
]

# 执行匹配并输出结果
for case in test_cases:
    match_result = re.match(pattern, case)
    if match_result:
        print(f"第一部分提取结果:{match_result.group(1)}")
        print(f"第二部分提取结果:{match_result.group(2)}")
        print("---")

输出结果

第一部分提取结果:SubProduct
第二部分提取结果:2ndMod-Patch
---
第一部分提取结果:1stMod-SubProduct
第二部分提取结果:2ndMod-Patch
---

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 10:55:16