How to extract all numbers before and after a specific keyword?

Viewed 188

I am new to R and have spent the last 2 months on this website trying to learn more. I want to pull information from a dataset that has a specific keyword and then those that DO have that keyword, I want to pull the 5 words before and after that keyword. Then I want to know what number(s) they have near them in that same sentence.

To explain the "Why", I have a list of tickets I want to pull all the Titles of the tickets. Then I want to know from that list of those tickets which are requesting for additional Storage. If they are, I want to know how MUCH storage they are asking for, and then later I will create actions depending on how much storage they're asking for (but that is later).

Example of the code I have completed so far (it's a bit messy, I am working on a better/cleaner way still, I'm very new to R).

The keyword I'm searching for: Storage

Dataframe referenced as: DF, DF2, DF3 etc.

Column from DF: Title

#Check for keyword#
grep("storage", DF$Title, ignore.case=true)

#Pull words before and after keywords, this is case sensitive for some reason so I have to do it twice and merge the data frames, it also creates a list instead of a data frame so I have to change that into a data frame...Messy I know#
DF2 <- stringr::str_extract_all(DF$Title, "([^\\s]+\\s){0,5}Storage(\\s[^\\s]+){0,5}")

#Turn list into dataframe#
DF3 <- do.call(rbind.data.frame, DF2)

#Pull words before and after but in lower case, same as step two#
DF4 <- stringr::str_extract_all(DF$Title, "([^\\s]+\\s){0,5}storage(\\s[^\\s]+){0,5}")

#Turn list into dataframe#
DF5 <- do.call(rbind.data.frame, DF4)

#Change column names ( I have to do this to merge them via rbind)
DF6 <- setnames(DF3, c("Keyword")
DF7 <- setnames(DF5, c("Keyword")

#Merge both data frames together#
DF6 <- rbind(DF6,Df7)

I want to check the amount of storage being requested, so I'm trying to look for a number referencing GB or TB, etc. I've tried numerous code but a lot only pull the numbers or number right after a keyword, not all numbers in the sentence.

Example of what I've tried with it not working

DFTest <- as.integer(str_match(DF6, "(?i\\bGB:?\\s*(\\d+")[,2])
1 Answers

The following approach will extract all numbers before a specific keyword (this case I used AND), or after a keyword. You can change your keyword in the regex pattern.

library(tidyverse)

df <- data.frame(obs = 1:5, COL_D = c("2019AND", "AND1999", "101AND", "AND12", "20AND1999999"))

df2 <- df %>% 
  mutate(Extracted_Num = str_extract_all(COL_D, regex("\\d+(?=AND)|(?<=AND)\\d+")))

# obs        COL_D Extracted_Num
# 1   1      2019AND          2019
# 2   2      AND1999          1999
# 3   3       101AND           101
# 4   4        AND12            12
# 5   5 20AND1999999   20, 1999999
Related