可以使用正则表达式来解决这个问题。下面是一个Python代码示例:
import re
def replace_content(text):
# 替换从 (color 到 ;) 的内容
text = re.sub(r'\(color.*?;\)', '', text)
# 替换从 ? 开始到 ) 的内容
text = re.sub(r'\?.*?\)', '', text)
return text
# 测试
text = "This is a test (color red;) sentence. Can you help me? (color blue;) Sure, I can help you.)"
replaced_text = replace_content(text)
print(replaced_text)
输出结果为:
This is a test sentence. Can you help me? Sure, I can help you.
在上述代码中,首先使用re.sub()
函数来替换从(color
到;)
的内容,正则表达式\(color.*?;\)
表示匹配以(color
开头,以;
结尾的内容,并使用空字符串进行替换。
然后,再次使用re.sub()
函数来替换从?
开始到)
的内容,正则表达式\?.*?\)
表示匹配以?
开头,以)
结尾的内容,并使用空字符串进行替换。
最后,将替换后的文本返回。