不使用正则表达式提取字符串中((与))间内容的方法
不使用正则提取指定标记间内容的方法
针对字符串 "((the)) weather is usually good ((when)) its ((spring))",可以通过字符串的查找与截取方法实现,步骤如下:
- 初始化空列表存储提取结果,设置初始查找位置为0
- 循环执行以下操作:
- 从当前位置开始查找标记
((的起始索引 - 若找不到
((,直接跳出循环 - 从找到的
((索引+2的位置开始,查找对应))的起始索引 - 若找到
)),截取((结束到))开始之间的子串,加入结果列表 - 更新当前查找位置为
))索引+2的位置,继续下一轮查找
- 从当前位置开始查找标记
用Python代码实现的示例:
s = "((the)) weather is usually good ((when)) its ((spring))" result = [] start = 0 while True: open_tag = s.find('((', start) if open_tag == -1: break close_tag = s.find('))', open_tag + 2) if close_tag == -1: break content = s[open_tag+2 : close_tag] result.append(content.strip()) # 可选:去除内容前后可能的空格 start = close_tag + 2 print(result) # 输出: ['the', 'when', 'spring']
这个方法通过逐次定位标记位置,手动截取目标内容,完全不需要依赖正则表达式。
内容的提问来源于stack exchange,提问作者user20137453
相关产品推荐
相关产品推荐

