我想在字符串中搜索单个字符,并将它们与字符串
中的下一个单词连接起来例如:
INPUT : "B 123, G BLOCK SUN SHINE APPTS"
OUTPUT : "B123, GBLOCK SUN SHINE APPTS"
我曾尝试使用str_extract从字符串中提取单个字符元素,但发现它只会导致第一次出现该模式。
> str_extract("B 123, G BLOCK SUN SHINE APPTS", "[a-zA-Z]{1}")
[1] "B"
对此的任何帮助都会很棒。感谢
答案 0 :(得分:6)
您可以使用gsub
执行此操作。
x <- 'B 123, G BLOCK SUN SHINE APPTS'
gsub('(?<=\\b[a-zA-Z]\\b)\\s+', '', x, perl=T)
[1] "B123, GBLOCK SUN SHINE APPTS"
答案 1 :(得分:3)
例如,你可以这样做:
## extracts words
xx <- unlist(strsplit('B 123, G BLOCK SUN SHINE APPTS'," "))
## get one letter words
idx <- which(nchar(xx)==1)
## concatenate them with the next words then replace them in the origin
xx[idx+1] <- paste0(xx[idx] ,xx[idx + 1 ])
## remove them one letter words and join all words
paste(xx[-idx],collapse=' ')
[1] "B123, GBLOCK SUN SHINE APPTS"