Python高效提取两个指定子串中间内容及无标记字符串的实现方法
Python代码修正方案
原代码问题点
- 未预先判断字符串是否同时包含
asdf:5;和123jasd两个标记子串,直接硬切固定长度逻辑错误 - 没有考虑标记子串不在字符串首尾的情况,按固定首尾位置切片会得到错误内容
修正方案
方案1:字符串内置方法实现(无需引入额外库)
strings = ['stackasdf:5;iwantthis123jasdoverflow','iwantthistoo','asdf:5;python123jasd'] start = 'asdf:5;' end = '123jasd' for s in strings: if start in s and end in s: start_pos = s.index(start) + len(start) end_pos = s.index(end) print(s[start_pos:end_pos]) else: print(s)
方案2:正则表达式实现(更简洁)
import re strings = ['stackasdf:5;iwantthis123jasdoverflow','iwantthistoo','asdf:5;python123jasd'] # 非贪婪匹配两个标记中间的内容 pattern = r'asdf:5;(.*?)123jasd' for s in strings: res = re.search(pattern, s) print(res.group(1) if res else s)
两种方案运行后均可得到预期输出:
iwantthis iwantthistoo python
内容的提问来源于stack exchange,提问作者Learner
相关产品推荐
相关产品推荐

