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

如何提取字符串中每个方括号内的首个元素 附代码示例

以下是R语言环境下的两种实现方案:

方案1:正则表达式快速提取

依赖stringr包实现正则匹配,适合快速处理格式固定的同类字符串:

# 加载依赖包
library(stringr)

# 匹配所有[后面紧跟的第一个双引号包裹的内容
all_first_elements <- str_extract_all(x, '(?<=\\[").*?(?=")')[[1]]
# 提取前3个元素
target_res <- all_first_elements[1:3]

# 输出符合要求的格式
dput(target_res)

运行后输出结果为:
c("Multi & Flexi-Cap", "Large-Cap", "Large & Mid-Cap")


方案2:JSON解析(更稳定)

你提供的字符串本身就是合法的二维JSON数组片段,补全格式后直接解析即可,即使内容包含引号、逗号等特殊字符也不会出错:

# 加载依赖包
library(jsonlite)

# 补全为标准JSON格式后解析为矩阵
parsed_arr <- fromJSON(paste0("[", x, "]"))
# 提取所有子数组的第一个元素,取前3位
target_res <- parsed_arr[, 1][1:3]

# 输出符合要求的格式
dput(target_res)

运行结果和方案1完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:36:03