4

我有一个字符串:

s <- "test.test AS field1, ablh.blah AS field2, faslk.lsdf AS field3"

我想转换为:

"field1, field2, field3"

我知道正则表达式(\w+)(?:,|$)会提取我想要的字符串('field1'等),但我不知道如何用gsub.

4

2 回答 2

10
## 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"
于 2013-09-12T23:16:46.517 回答
0

gsubfn 包strapplyc中,可以使用一个特别简单的正则表达式来完成它,该表达式提取后面的每个单词字符串(如果该字段可以包含非单词字符,则用适当的表达式替换,例如任何不是空格的字符或逗号:):" AS "\\w[^ ,]

> library(gsubfn)
> strapplyc(s, " AS (\\w+)", simplify = toString)[[1]]
[1] "field1, field2, field3"
于 2013-11-04T23:21:38.997 回答