如何删除字符串中从开头到包含']'为止的所有字符
实现方案
核心逻辑为匹配字符串开头所有连续被[]包裹的片段(包含括号本身),直接删除即可,以下是不同开发场景的实现代码:
Python 实现
- 正则匹配方案(适配给出的示例场景)
import re def remove_prefix_brackets(input_str): # 匹配开头所有连续的[xxx]格式片段,替换为空 return re.sub(r'^(\[.*?\])+', '', input_str) # 测试用例 a = "[12] hi how are you [1]" b = "[13][14] hello" print(remove_prefix_brackets(a)) # 输出: hi how are you [1],如果需要去掉前导空格可加.strip() print(remove_prefix_brackets(b)) # 输出: hello
- 如果仅需要删除到第一个
](包含该字符),可以用更轻量的字符串查找方法:
def remove_to_first_right_bracket(input_str): right_idx = input_str.find(']') return input_str[right_idx+1:] if right_idx != -1 else input_str
JavaScript 实现
function removePrefixBrackets(str) { return str.replace(/^(\[.*?\])+/, '') } // 测试用例 const a = "[12] hi how are you [1]" const b = "[13][14] hello" console.log(removePrefixBrackets(a)) console.log(removePrefixBrackets(b))
Shell sed 命令实现
echo "[13][14] hello" | sed -E 's/^(\[[^]]*\])+//'
内容的提问来源于stack exchange,提问作者chaithanya N
相关产品推荐
相关产品推荐

