R:提取逗号之间的单词?

问题描述 投票:-1回答:1

说我有一个字符串,其中的各个单词之间用逗号隔开。

"Hello, 1000, "Oh shit, a comma", helloagain"

我想使用这样的字符串,并给定值n,请提取第n个和第(n + 1)个逗号之间的单词。

例如,如果n = 1,我想提取1000。如果是n = 2,我要提取"Oh shit, a comma"。依此类推。

我该怎么做?

请注意,逗号之间的单词可以在引号中包含逗号...,也可以为空,例如该字符串也可以是

"Hello,, 1000"

n = 1的位置,我们需要单词""

r string word
1个回答
0
投票
假设您打算将带引号的字符串放在一起(不分割),这是一种尝试:

s <- "Hello, 1000, \"Oh shit, a_comma\", helloagain" gre <- gregexpr("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'", s) unlist(lapply(regmatches(s, gre), function(z) { ifelse(grepl('^"', z), z, strsplit(gsub('"', '', z), "[ ,]+")) })) # [1] "Hello" "1000" "\"Oh shit, a_comma\"" "" # [5] "helloagain"

从这里开始只是简单的索引。
© www.soinside.com 2019 - 2024. All rights reserved.