文字列内の特定の単語で囲まれた部分文字列を削除する方法


方法1: 正規表現を使用する方法(Python)

import re
def remove_substring_with_words(string, start_word, end_word):
    pattern = rf"\b{start_word}\b.*?\b{end_word}\b"
    result = re.sub(pattern, "", string)
    return result
# 使用例
string = "This is a sample string. [start_word]This part should be removed[end_word]."
start_word = "[start_word]"
end_word = "[end_word]"
result = remove_substring_with_words(string, start_word, end_word)
print(result)

方法2: インデックスを使用する方法(Python)

def remove_substring_with_words(string, start_word, end_word):
    start_index = string.find(start_word)
    end_index = string.find(end_word) + len(end_word)

    if start_index != -1 and end_index != -1:
        result = string[:start_index] + string[end_index:]
    else:
        result = string

    return result
# 使用例
string = "This is a sample string. [start_word]This part should be removed[end_word]."
start_word = "[start_word]"
end_word = "[end_word]"
result = remove_substring_with_words(string, start_word, end_word)
print(result)