我有一个字符串:
s <- "test.test AS field1, ablh.blah AS field2, faslk.lsdf AS field3"
我想转换为:
"field1, field2, field3"
我知道正则表达式(\w+)(?:,|$)
会提取我想要的字符串('field1'等),但我不知道如何用gsub
.
## Preparation
s <- "test.test AS field1, ablh.blah AS field2, faslk.lsdf AS field3"
pat <- "(\\w+)(?:,|$)" ## Note the doubly-escaped \\w
## Use the powerful gregexpr/regmatches one-two punch
m <- gregexpr(pat, s)
paste(regmatches(s, m)[[1]], collapse=" ")
# [1] "field1, field2, field3"
在gsubfn 包strapplyc
中,可以使用一个特别简单的正则表达式来完成它,该表达式提取后面的每个单词字符串(如果该字段可以包含非单词字符,则用适当的表达式替换,例如任何不是空格的字符或逗号:):" AS "
\\w
[^ ,]
> library(gsubfn)
> strapplyc(s, " AS (\\w+)", simplify = toString)[[1]]
[1] "field1, field2, field3"