Extract String Between First and Second Whitespace

Viewed 187

I'm trying to extract a certain portion of the text in a column - I only want the text between the first and second whitespace - in this case the manufacture year. The field is in column "Detail" within the dataframe "data". This is the structure which is consistent:

Used 2014 Toyota Camry

I'm only interested in capturing the "2014" within this field:

Here is what I've tried:

sub(".*?\\s+(.*)\\s.*", "\\1", "Used 2014 Toyota Camry", perl=TRUE)

Help is much appreciated.

3 Answers

You were very close, you also need to limit your capture group.

sub(".*?\\s+(.*?)\\s.*", "\\1", "Used 2014 Toyota Camry")
#[1] "2014"

If that's only first and second white space, this solution can also be used:

strsplit("Used 2014 Toyota Camry", " ")[[1]][2]
[1] "2014"

We could do

readr::parse_number(str1)
[1] 2014

Or in base R

 trimws(str1, whitespace = "\\D+")
[1] "2014"

data

str1 <-  "Used 2014 Toyota Camry"
Related