The text_replace() function

Use the metro dataset to create a gt table. With cols_merge(), we’ll 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 text_replace(). The pattern value of "\\((.*?)\\)" will match on text between parentheses, and the inner "(.*?)" is a capture group. The replacement value of "<br>(<em>\\1</em>)" puts the capture group text "\1" within <em> tags, wraps literal parentheses around it, and prepends a line break tag.

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