4

I have a string:

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

I want to convert to:

"field1, field2, field3"

I know that the regular expression (\w+)(?:,|$) will extract the strings I want ('field1,' etc) but I can't figure out how to extract it with gsub.

2 Answers 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"
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, that's what I was trying to do and just couldn't quite get it to work.
Glad to hear it helped. Cheers.
0

With strapplyc in the gsubfn package one can do it with a particularly simple regular expression which extracts each string of word characters that follows " AS " (If the field can contain non-word characters then replace \\w with the appropriate expression, for example any char that is not a space or comma: [^ ,]):

> library(gsubfn)
> strapplyc(s, " AS (\\w+)", simplify = toString)[[1]]
[1] "field1, field2, field3"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.