Extract from string using regex

I have a line:

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 retrieve the lines I want ('field1,' etc.), but I cannot figure out how to extract it with gsub .

+4
source share
2 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" 
+10
source

With strapplyc in the gsubfn package, you can do this with a particularly simple regular expression that extracts every line of word characters following " AS " (If the field can contain characters without words, replace \\w with the corresponding 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" 
0
source

Source: https://habr.com/ru/post/1501954/


All Articles