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

技术问询:如何删除字符串中除首次出现外的所有指定子串

How to Remove All Instances of a Substring Except the First Occurrence

Alright, let's tackle this problem step by step. The core goal here is to preserve the first occurrence of a specified substring query in a given string text, while deleting every subsequent instance of that substring. This solution works for any general scenario—no matter what your text or query looks like.

Core Approach

Here's the straightforward, easy-to-follow logic we'll use:

  1. Locate the first match: Find where the query first appears in text. If it doesn't exist at all, just return the original string.
  2. Split the string: Divide text into two distinct parts:
    • The prefix: Everything from the start of the string up to (and including) the first occurrence of query.
    • The suffix: The remaining portion of the string that comes right after the first query.
  3. Clean the suffix: Strip out all instances of query from the suffix.
  4. Combine the parts: Attach the cleaned suffix back to the prefix, and you'll have your desired result.

Example Implementation (Python)

Let's turn this logic into a reusable function. This works for all standard string scenarios, including special characters, empty strings, and edge cases:

def keep_first_remove_rest(text, query):
    # Find the starting index of the first occurrence of the query
    first_match_index = text.find(query)
    
    # If the query doesn't exist in the text, return the original text
    if first_match_index == -1:
        return text
    
    # Split into prefix (includes first query) and suffix (everything after)
    prefix = text[:first_match_index + len(query)]
    suffix = text[first_match_index + len(query):]
    
    # Remove all instances of query from the suffix
    cleaned_suffix = suffix.replace(query, '')
    
    # Combine and return the final string
    return prefix + cleaned_suffix

Real-World Test Cases

Let's put this function to work with some common scenarios:

  • Basic usage:
    • Input: text = "cat dog cat bird cat fish", query = "cat"
    • Output: "cat dog bird fish"
  • Special characters:
    • Input: text = "@@header@@content@@footer@@", query = "@@"
    • Output: "@@headercontentfooter"
  • Edge case: query only appears once:
    • Input: text = "hello world", query = "world"
    • Output: "hello world" (no changes needed)
  • Edge case: query is longer than text:
    • Input: text = "short", query = "longerstring"
    • Output: "short" (returns original text)

Key Notes

  • This approach is efficient, as it only scans the string a few times (once to find the first match, once to clean the suffix).
  • It handles all valid string inputs, including empty strings, whitespace-only strings, and case-sensitive matches. If you need case-insensitive behavior, you can adjust the find method to use lower() on both text and query first.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:31:47