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

如何利用PATINDEX从两种模式字符串中提取指定子串?

Solution for Extracting Parts of Your String Format

Hey Sophie, nice questions—let’s walk through how to solve both of these easily.

Question 1: Extracting the second part (XYZ789)

Your strings follow a consistent [Part1]-[Middle]-[Part2] structure, so there are two straightforward ways to grab the second part:

Method 1: Split the string by hyphens

Since the string is separated by -, splitting it into a list lets you access each part directly. For example, in Python:

my_string = "ABC123-S-XYZ789"
parts = my_string.split("-")
second_part = parts[2]  # This gives you "XYZ789"

Splitting on - turns the string into a 3-element list, where the third element (index 2, since we count from 0) is your target.

Method 2: Use regular expressions

If you prefer regex, you can match the pattern to capture the second part directly. This works even if you want to target it explicitly:

import re
my_string = "ABC123-P-XYZ789"
match = re.search(r"-[SP]-(\w+)", my_string)
second_part = match.group(1)  # Returns "XYZ789"

For extra flexibility (in case the middle part ever changes beyond S/P), use r"-.-(\w+)" instead—it’ll match any single character between the hyphens.

Question 2: Handling both -S- and -P- patterns without prior knowledge

Good news—you don’t need to pre-check which pattern you’re dealing with! Both methods above work for either format automatically:

  • The split method doesn’t care what’s in the middle; it just splits on all hyphens, so you always get the third element as your second part.
  • For regex, you can use a pattern that ignores the middle section entirely while capturing both parts you care about:
    import re
    my_string = "ABC123-S-XYZ789"  # or "ABC123-P-XYZ789"
    match = re.search(r"(\w+)-\w+-(\w+)", my_string)
    first_part = match.group(1)  # "ABC123"
    second_part = match.group(2)  # "XYZ789"
    

This regex matches word characters for the first part, any single word character in the middle, then word characters for the second part—perfect for both your patterns.

No matter which approach you pick, you won’t have to distinguish between -S- and -P- upfront; the code handles both cases seamlessly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:09:18