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

如何查找字符串中以'a'开头、以'b'结尾的子串?

Extracting All 'a'-to-'b' Substrings from a String

Got it, let's break down how to solve this problem. You need to pull out every substring from 'abdadqdqbdabdabdawb' that starts with 'a' and ends with 'b', with the expected output being ['ab', 'adqdqb', 'ab', 'ab', 'awb']. Here's a straightforward Python solution tailored to your needs:

Step-by-Step Code Solution

s = 'abdadqdqbdabdabdawb'
matched_substrings = []
current_start = None

for index, char in enumerate(s):
    # Mark the start of a potential substring when we hit an unpaired 'a'
    if char == 'a':
        current_start = index
    # Extract the substring when we hit a 'b' that pairs with the last 'a'
    elif char == 'b' and current_start is not None:
        matched_substrings.append(s[current_start:index + 1])
        # Reset start to avoid reusing the same 'a' for multiple 'b's
        current_start = None

print(matched_substrings)

How This Logic Works

  • We initialize an empty list matched_substrings to store our results, and current_start to track the position of the last unpaired 'a' we found.
  • As we loop through each character in the string:
    • When we encounter an 'a', we update current_start to its index—this sets the starting point for our next candidate substring.
    • When we hit a 'b' and we have an unpaired 'a' (meaning current_start isn’t None), we slice the string from current_start to the current index (inclusive), add this substring to our list, then reset current_start so we don’t pair that same 'a' with another 'b'.
  • This ensures we capture non-overlapping, sequential a-to-b substrings exactly as your expected output requires.

Output Verification

Running the code above will print:

['ab', 'adqdqb', 'ab', 'ab', 'awb']

Which matches your desired result perfectly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:52:00