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

如何用Python3正则提取含重复前缀的多选项重叠匹配字符串

Solution for Extracting Prepend-Prefixed Options from Job Description

Got it, let's fix this! Your goal is to split the job requirement on "or" and attach the shared prefix to each resulting item—your initial regex only grabbed the prefix, so we need to adjust to capture both the prefix and the options, then combine them.

Approach 1: For Two Options (Exact Match to Your Example)

Use a regex that captures three groups: the shared prefix, the first option, and the second option. Then we just combine the prefix with each option to build our result list.

import re

str1 = '2+ years in buy side research or accounting'
# Regex to capture prefix, first option, second option
pattern = re.compile(r'^([0-9+]+ years in) (.+?) or (.+)$')
match = pattern.match(str1)

if match:
    prefix = match.group(1)
    result = [
        f"{prefix}{match.group(2)}",
        f"{prefix}{match.group(3)}"
    ]

print(result)
# Output: ['2+ years in buy side research', '2+ years in accounting']

Approach 2: For Multiple "or" Options (More Flexible)

If you might encounter cases with more than two options (like "2+ years in buy side research or accounting or financial analysis"), this method splits all options after capturing the prefix:

import re

str1 = '2+ years in buy side research or accounting or financial analysis'
pattern = re.compile(r'^([0-9+]+ years in) (.+)$')
match = pattern.match(str1)

if match:
    prefix = match.group(1)
    # Split the options part and strip whitespace from each item
    options = [opt.strip() for opt in match.group(2).split('or')]
    # Combine prefix with each option
    result = [f"{prefix}{opt}" for opt in options]

print(result)
# Output: ['2+ years in buy side research', '2+ years in accounting', '2+ years in financial analysis']

Why Your Initial Regex Didn't Work

Your original pattern only targeted the prefix ([0-9+]+ years|year), so it couldn't capture the subsequent options we need to pair with that prefix. The updated regexes first isolate the shared prefix, then capture the list of options to combine with it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:31:00