仅当 R 中不存在时才在字符串中的逗号后添加 space
Add a space after commas in a string only if it doesn't exist in R
比如我有
a=c("Jack and Jill,went up the, hill,to,fetch a pail,of, water")
我想做的是在逗号后添加 space 当且仅当逗号后跟字母表时
这样我的输出看起来像这样
"Jack and Jill, went up the, hill, to, fetch a pail, of, water"
这是我试过的
gsub("/,(?![ ])/, ", " ",a)
但没有给我想要的结果。
任何帮助将非常感激。谢谢
我们可以使用gsub
来匹配一个逗号(,
)后跟作为一个组捕获的任何字母(([A-Za-z])
)然后用,
替换它通过 space 和该捕获组的反向引用 (\1
)
gsub(",([A-Za-z])", ", \1", a)
#[1] "Jack and Jill, went up the, hill, to, fetch a pail, of, water"
或使用[[:alpha:]]
gsub(",([[:alpha:]])", ", \1", a)
#[1] "Jack and Jill, went up the, hill, to, fetch a pail, of, water"
比如我有
a=c("Jack and Jill,went up the, hill,to,fetch a pail,of, water")
我想做的是在逗号后添加 space 当且仅当逗号后跟字母表时 这样我的输出看起来像这样
"Jack and Jill, went up the, hill, to, fetch a pail, of, water"
这是我试过的
gsub("/,(?![ ])/, ", " ",a)
但没有给我想要的结果。 任何帮助将非常感激。谢谢
我们可以使用gsub
来匹配一个逗号(,
)后跟作为一个组捕获的任何字母(([A-Za-z])
)然后用,
替换它通过 space 和该捕获组的反向引用 (\1
)
gsub(",([A-Za-z])", ", \1", a)
#[1] "Jack and Jill, went up the, hill, to, fetch a pail, of, water"
或使用[[:alpha:]]
gsub(",([[:alpha:]])", ", \1", a)
#[1] "Jack and Jill, went up the, hill, to, fetch a pail, of, water"