如何在Python中将括号内的所有子串保存到数组中
问题描述
现有字符串:
obs1 = "3341 - SSS - ELO CRED - (48,00) 4526 - SSS 7837 - SSS - MASTER DEB - (25,00) 2830 - SSS - VISA CRED - (35,00)"
使用以下自定义函数:
def find_between( s, first, last ): try: start = s.index( first ) + len( first ) end = s.index( last, start ) return s[start:end] except ValueError: return ""
调用print(find_between(obs1, "(", ")"))仅返回第一个匹配的48,00,但需要提取所有括号内的数值48,00、25,00、35,00并保存到数组中,该如何实现?
解决方案
方法一:使用正则表达式(推荐)
Python的re模块可以高效匹配所有符合格式的内容,直接提取目标数值:
import re obs1 = "3341 - SSS - ELO CRED - (48,00)\n\n4526 - SSS\n\n7837 - SSS - MASTER DEB - (25,00)\n\n2830 - SSS - VISA CRED - (35,00)" # 用正则匹配所有括号内的内容,非贪婪模式避免匹配到多个括号的情况 matches = re.findall(r'\((.*?)\)', obs1) print(matches) # 输出: ['48,00', '25,00', '35,00']
正则说明:
\(:转义后匹配左括号(括号在正则中属于特殊字符,需转义)(.*?):非贪婪捕获组,匹配括号间的任意字符,确保只取到最近的右括号\):转义后匹配右括号re.findall()会自动收集所有匹配到的捕获内容,直接得到目标列表。
方法二:修改原函数实现循环查找
如果不想依赖正则,可以改造原函数,通过循环遍历所有匹配项:
def find_all_between(s, first, last): results = [] current_pos = 0 while True: try: # 找到左括号的位置并偏移到括号后 start = s.index(first, current_pos) + len(first) # 找到当前左括号对应的右括号位置 end = s.index(last, start) # 提取内容并加入结果列表 results.append(s[start:end]) # 更新起始位置,继续查找下一个匹配 current_pos = end + len(last) except ValueError: # 没有找到更多匹配时退出循环 break return results obs1 = "3341 - SSS - ELO CRED - (48,00)\n\n4526 - SSS\n\n7837 - SSS - MASTER DEB - (25,00)\n\n2830 - SSS - VISA CRED - (35,00)" matches = find_all_between(obs1, "(", ")") print(matches) # 输出: ['48,00', '25,00', '35,00']
内容的提问来源于stack exchange,提问作者Panther Motos
相关产品推荐
相关产品推荐

