gpt4 book ai didi

r - 仅当 R 中不存在时才在字符串中的逗号后添加空格

转载 作者:行者123 更新时间:2023-12-05 01:44:56 25 4
gpt4 key购买 nike

比如我有

a=c("Jack and Jill,went up the, hill,to,fetch a pail,of, water")

我想做的是当且仅当逗号后跟字母表时才在逗号后添加空格这样我的输出看起来像这样

 "Jack and Jill, went up the, hill, to, fetch a pail, of, water"

这是我试过的

gsub("/,(?![ ])/, ", " ",a)

但没有给我想要的结果。任何帮助将非常感激。谢谢

最佳答案

我们可以使用 gsub 来匹配逗号 (,) 后跟任何字母 (([A-Za-z]))作为一个组捕获,然后将其替换为 后跟一个空格和该捕获组的反向引用 (\\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"

关于r - 仅当 R 中不存在时才在字符串中的逗号后添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44155594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com