跟踪R中字符串中的单个字符

use*_*217 1 regex string r

我想在字符串中搜索单个字符,并将它们与字符串中的下一个单词连接起来

例如:

INPUT :  "B 123, G BLOCK SUN SHINE APPTS"
OUTPUT : "B123, GBLOCK SUN SHINE APPTS"
Run Code Online (Sandbox Code Playgroud)

我曾尝试使用str_extract从字符串中提取单个字符元素,但发现它只导致模式的第一次出现.

> str_extract("B 123, G BLOCK SUN SHINE APPTS", "[a-zA-Z]{1}")
[1] "B"
Run Code Online (Sandbox Code Playgroud)

对此的任何帮助都会很棒.谢谢

hwn*_*wnd 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"
Run Code Online (Sandbox Code Playgroud)