r - 从字符串中提取第一个元素
问题描述
我想从 c([a,b],[c,d]) 的方括号中提取第一个元素。请参阅下面的示例 -
x <- "[\"Multi & Flexi-Cap\", \"Multi & Flexi Cap Fund\"], [\"Large-Cap\", \"Large Cap Fund\"], [\"Large & Mid-Cap\", \"Large & Mid Cap Fund\"], [\"Mid-Cap\", \"Mid Cap Fund\"], [\"Small-Cap\", \"Small Cap Fund\"], [\"ELSS\", \"ELSS (Tax Savings)\"], [\"Dividend Yield\", \"Dividend Yield\"], [\"Equity - Sectoral\", \"Sectoral/Thematic\"], [\"Contra\", \"Contra Fund\"], [\"Focused Fund\", \"Focused Fund\"], [\"Value\", \"Value Fund\"], [\"RGESS\", \"RGESS\"], [\"Equity - Other\", \"Equity - Other\"]"
前 3 个括号的期望输出 [ ]
c("Multi & Flexi-Cap", "Large-Cap", "Large & Mid-Cap")
解决方案
使用stringr
你可以尝试:
x <- "[\"Multi & Flexi-Cap\", \"Multi & Flexi Cap Fund\"], [\"Large-Cap\", \"Large Cap Fund\"], [\"Large & Mid-Cap\", \"Large & Mid Cap Fund\"], [\"Mid-Cap\", \"Mid Cap Fund\"], [\"Small-Cap\", \"Small Cap Fund\"], [\"ELSS\", \"ELSS (Tax Savings)\"], [\"Dividend Yield\", \"Dividend Yield\"], [\"Equity - Sectoral\", \"Sectoral/Thematic\"], [\"Contra\", \"Contra Fund\"], [\"Focused Fund\", \"Focused Fund\"], [\"Value\", \"Value Fund\"], [\"RGESS\", \"RGESS\"], [\"Equity - Other\", \"Equity - Other\"]"
library(stringr)
unlist(str_extract_all(x, "(?<=\\[\\\\?[:punct:])[A-z &-]*(?=\\\\?)"))
#> [1] "Multi & Flexi-Cap" "Large-Cap" "Large & Mid-Cap"
#> [4] "Mid-Cap" "Small-Cap" "ELSS"
#> [7] "Dividend Yield" "Equity - Sectoral" "Contra"
#> [10] "Focused Fund" "Value" "RGESS"
#> [13] "Equity - Other"
由reprex 包于 2021-08-27 创建 (v2.0.0 )
推荐阅读
- api - 使用 Reolink RLC-820A api 抓图
- mysql - Kubernetes Dump mysql 并恢复 Mysql
- jsf - PrimeFaces 10 移除方法 RadioButtonGroup.getSelectItems() 替换
- npm - 如何使用“yarn”或“npm”列出特定类型的依赖项
- azure - 在雪花中添加具有默认值的列,但在 ADF 中复制数据活动(从具有所需列的文本文件复制)失败
- regex - Jmeter 通过数据源将正则表达式传递给正则表达式提取
- javascript - src\components\Home.js Line 6:10: 'Container' is not defined react/jsx-no-undef
- gitlab - 如何为推送运行单个作业并为日程安排运行“矩阵”作业?
- vba - 退出幻灯片放映模式时停止“循环播放”
- android - 在片段中使用 Volley 时出现 com.android.volley.ClientError 错误