Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a better way to replace multiple patterns inside of a string?

Whenever I need to do text replacement, it’s rare that I only have to replace one pattern. I often find myself stringing together multiple str_replace_all() calls, one after another. The example code below feels very repetitive. Is there a way to do this with only one call to str_replace_all()?

library(dplyr)
library(stringr)

text <- r'(mother, father, grandmother, and grandfather)'

# is there a better way to do this?
text %>% 
  str_replace_all(
    pattern = r'(\bmother\b)',
    replacement = 'mom'
  ) %>% 
  str_replace_all(
    pattern = r'(\bfather\b)',
    replacement = 'dad'
  ) %>% 
  str_replace_all(
    pattern = 'grandmother',
    replacement = 'grandma'
  ) %>% 
  str_replace_all(
    pattern = 'grandfather',
    replacement = 'grandpa'
  ) %>% 
  str_replace_all(
    pattern = r'(\band\b)',
    replacement = '&'
  )
#> [1] "mom, dad, grandma, & grandpa"

Created on 2023-12-12 with reprex v2.0.2

I’m imagining something with a lookup table.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df_lookup <-
  tribble(
    ~pattern,           ~replacement,
    r'(\bmother\b)',    'mom',
    r'(\bfather\b)',    'dad',
    'grandmother',      'grandma',
    'grandfather',      'grandpa',
    r'(\band\b)',       '&'
  )

>Solution :

You can perform multiple str_replace as follows:

str_replace_all(text, 
    c(
        r'(\bmother\b)' = "mom", 
         r'(\bfather\b)' = "dad", 
        'grandmother' = "grandma", 
        'grandfather' = "grandpa",
        r'(\band\b)' = "&")
    )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading