str_replace with capture groups

I'm having trouble with stringr and capture groups. I want to replace the underscore between the numbers with a hyphen.

I have this:

df <- tibble::tribble(
                            ~long, ~value,
     "Age_groups_0_4_years_Persons",     20,
    "Age_groups_5_14_years_Persons",     74,
   "Age_groups_15_19_years_Persons",     29,
   "Age_groups_20_24_years_Persons",     32,
   "Age_groups_25_34_years_Persons",     38
)

# this doesn't work properly -----------------------------
df %>% 
  mutate(incorrect = str_replace(long, "\\d{1,2}(_)\\d{1,2}", "-"))

# # A tibble: 5 × 3
# long                           value incorrect                 
# <chr>                          <dbl> <chr>                     
# 1 Age_groups_0_4_years_Persons      20 Age_groups_-_years_Persons
# 2 Age_groups_5_14_years_Persons     74 Age_groups_-_years_Persons
# 3 Age_groups_15_19_years_Persons    29 Age_groups_-_years_Persons
# 4 Age_groups_20_24_years_Persons    32 Age_groups_-_years_Persons
# 5 Age_groups_25_34_years_Persons    38 Age_groups_-_years_Persons

# desired output ----------------------------------------
# # A tibble: 5 × 2
# long                           value
# <chr>                          <dbl>
# 1 Age groups 0-4 years Persons      20
# 2 Age groups 5-14 years Persons     74
# 3 Age groups 15-19 years Persons    29
# 4 Age groups 20-24 years Persons    32
# 5 Age groups 25-34 years Persons    38

Any ideas?

This works:

df %>% 
  mutate(correct = str_replace(long, "(\\d{1,2})(_)(\\d{1,2})", "\\1-\\3"))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.