The text_replace() function

Use metro to create a gt table. Merge the name and caption columns together but only if caption doesn’t have an NA value (the special pattern syntax of "{1<< ({2})>>“} takes care of this). This merged content is now part of the name column. We’d like to modify this further wherever there is text in parentheses: (1) make that text italicized, and (2) introduce a line break before the text in parentheses. We can do this with the text_replace() function.

metro |>
  dplyr::select(name, caption, lines) |>
  dplyr::slice(110:120) |>
  gt() |>
  cols_merge(
    columns = c(name, caption),
    pattern = "{1}<< ({2})>>"
  ) |>
  text_replace(
    locations = cells_body(columns = name),
    pattern = "\\\\((.*?)\\\\)",
    replacement = "<br>(<em>\\\\1</em>)"
  )
name lines
Oberkampf 5, 9
Ourcq 5
Place d'Italie 5, 6, 7
Porte de Pantin (Parc de la Villette) 5
Quai de la Rapée 5
Richard-Lenoir 5
Saint-Marcel 5
Bel-Air 6
Bercy 6, 14
Bir-Hakeim (Tour Eiffel) 6
Boissière 6