Issue removing two patterns (string and numbers) using regex in R -
i trying remove 2 patterns using str_replace in r.
the patterns remove \\d+_ , baskets
i first tried:
> library(stringr) > variables <- c("1_smallbaskets", "2_medium", "3_high") > str_replace(variables, "baskets|\\d+_", "") [1] "smallbaskets" "medium" "high" as far can make out, pattern \\d+_ comes first replaced moves onto next without replacing baskets
i tried making expression greedy (example below), seems checking expression baskets
> str_replace(variables, "baskets|\\d+_/g", "") [1] "1_small" "2_medium" "3_high" i have tested syntax small|high works, i.e. replaces small or high, don't understand why when trying replace digit , character same logic doesn't apply
with str_replace, replace the first occurrence. str_replace_all, replace all occurrences, matches inside 1 string. see code:
> library(stringr) > variables <- c("1_smallbaskets", "2_medium", "3_high") > str_replace(variables, "baskets|\\d+_", "") [1] "smallbaskets" "medium" "high" > str_replace_all(variables, "baskets|\\d+_", "") [1] "small" "medium" "high" also, can leverage gsub here:
> gsub("baskets|\\d+_", "", variables) [1] "small" "medium" "high"
Comments
Post a Comment