我正在努力提高基于数据库查询的自动文本生成的可读性。
有没有一种巧妙的方法来进行这些换人?要在1个命令而不是6个命令中执行以下操作?
x<-c("Te( )st", "Test()", "Test ()", "Test ( )", "Test ,,", "Test,, ", "Test , ")
out<-c("Test", "Test", "Test", "Test", "Test,", "Test, ", "Test,")
x<-gsub(pattern = "( ", replacement = "(", x, fixed = T)
x<-gsub(pattern = " )", replacement = ")", x, fixed = T)
x<-gsub(pattern = " ,", replacement = ",", x, fixed = T)
x<-gsub(pattern = "()", replacement = "", x, fixed = T)
x<-gsub(pattern = ",,", replacement = ",", x, fixed = T)
x<-gsub(pattern = " ,", replacement = ",", x, fixed = T)
您可以使用
x<-c("Te( )st", "Test()", "Test ()", "Test ( )", "Test ,,", "Test,, ", "Test , ")
gsub("\(\s*\)|\s+(?=[,)])|(?<=\()\s+|(,),+", "\1", x, perl=TRUE)
# => [1] "Test" "Test" "Test " "Test " "Test," "Test, " "Test, "
请在线查看R演示和regex演示详细信息:
(s*)|
-(
,零个或多个空白,然后是)
,或s+(?=[,)])|
-一个或多个空白,然后是,
或)
,或者(?<=()s+|
-一个或多个紧跟在(
字符前面的空白,或(,),+
-捕获到组1中的逗号,然后是一个或多个逗号
替换为Group 1值,即如果Group 1匹配,则替换为单个逗号,否则为空字符串。
您可以使用mgsub::mgsub
。
a = c("( ", " )", " ,", "()",",,") #pattern
b = c("(", ")", ",", "",",") #replacement
x<-c("Te( )st", "Test()", "Test ()", "Test ( )", "Test ,,", "Test,, ", "Test , ")
mgsub::mgsub(x, a, b, fixed = T)
#[1] "Te()st" "Test" "Test " "Test ()" "Test,," "Test, " "Test, "
您可能需要添加其他模式来获得所需的输出。
您可以使用multigsub
函数,它是R中gsub
函数的包装器。您可以在此处找到文档。
这是代码:
multigsub(c("(", ")", ",", "()", ",,", " ,"), c("(", ")", ",", "", ",", ","), x, fixed = T)