You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取字符串中括号内所有内容并实现循环遍历处理?

提取字符串中括号内内容并遍历的方法

要搞定这个需求,用正则表达式是最省心的办法,咱们一步步来实现:

1. 核心思路:正则匹配

字符串里的目标内容是[纬度, 经度]这种格式,咱们可以用正则r'\[([^\]]+)\]'来精准捕获:

  • \[:转义左方括号(因为它是正则里的特殊字符)
  • ([^\]]+):捕获组,匹配除右方括号外的所有字符,这样就能直接拿到括号里的经纬度内容
  • \]:转义右方括号,匹配结束位置

2. 完整代码示例

直接看可运行的Python代码:

import re

big_str = "[41.386263640000003, -81.494450689999994] 6 2011-08-28 19:02:28 yay. little league world series!\n[42.531041999999999, -82.90854831] 6 2011-08-28 19:02:29 i'm at holiday inn express suites & hotel roseville mi (31900 little mack ave., at masonic blvd., roseville)\n[39.992309570000003, -75.131119729999995] 6 2011-08-28 19:02:29 @_tweetthis what dorm r you in?\n[54.104106119999997, 28.336019929999999] 6 2011-08-28 19..."

# 提取所有括号内的内容
coordinate_strings = re.findall(r'\[([^\]]+)\]', big_str)

# 循环遍历并处理每个结果
for index, coord in enumerate(coordinate_strings):
    print(f"第{index+1}组坐标:{coord}")
    # 如果需要拆分纬度和经度,直接分割即可
    latitude, longitude = coord.split(', ')
    print(f"  纬度:{float(latitude)},经度:{float(longitude)}")

3. 代码细节说明

  • re.findall():会返回所有匹配到的捕获组内容,也就是每个括号里的经纬度字符串列表
  • enumerate():遍历的时候能拿到索引,方便区分不同的坐标组
  • 如果需要把字符串格式的经纬度转成数值类型,用float()直接转换就行

这样就能快速提取所有括号内的内容,并且循环遍历处理啦。

内容的提问来源于stack exchange,提问作者Jasmines

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:23:55