Extract digits and next string after from a character vector in R

Viewed 180

I am trying to solve an issue. I have a text vector, and I would like to extract the numbers from it and the next character (including space). I am using the stringr package for R but I can't seem to find a good solution for my problem. I would appreciate your help/ feedback.

library(tidyverse)
library(stringr)

my_text <- "This is my example vector. I have 15 oranges in the fridge, 12 apples in the room, 1 mother in my family, 1 father in my family, 12 siblings that live on 3 continents, and 45 randomthingsinmyhouse that I dont use"

# I would like to get the following information from my_text

"15 oranges" "12 apples" "1 mother" "1 father" "12 siblings" "45 randomthingsinmyouse"

I have tried using str_extract_all(my_text, "\\\d+") but obviously that only grabs digits.

str_extract_all(my_text, "\\d+")

# "15" "12" "1" "1" "12" "45"

I have tried using different regex patterns on the stringr package help page (https://stringr.tidyverse.org/articles/regular-expressions.html) but I can't seem to find one that works for my problem. Also the text after the numbers can be random - instead of apples and oranges I can have chickens, houses and so on. Any suggestions on how I should tackle this problem?

Thank you very much

1 Answers

Use the pattern to match one or more digits (\\d+) followed by one or more spaces (\\s+) and word (\\w+)

library(stringr)
str_extract_all(my_text, "\\d+\\s+\\w+")[[1]]
Related