Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract words between two periods using gsub

Tags:

regex

r

gsub

I have a text that looks like this:

txt <- "w.raw.median"

I want to extract the second word in between two periods (.), giving this output

> raw

But why this doesn't work

gsub(".*\\.", "", txt)

What's the right way to do it?

like image 472
neversaint Avatar asked Dec 07 '22 09:12

neversaint


2 Answers

Try this:

gsub(".*\\.(.*)\\..*", "\\1", txt)
[1] "raw"
like image 100
kohske Avatar answered Dec 21 '22 23:12

kohske


Also consider

strsplit(txt,'.',fixed=TRUE)[[1]][2]

for a (slightly) more readable version

like image 33
Jesse Anderson Avatar answered Dec 22 '22 00:12

Jesse Anderson