Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract from string using regular expression

Tags:

regex

r

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.

like image 490
Jeffrey Kramer Avatar asked Dec 26 '22 20:12

Jeffrey Kramer


1 Answers

## 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"
like image 98
Josh O'Brien Avatar answered Jan 13 '23 16:01

Josh O'Brien