Replace all occurrences of old_value with new_value. This method
gsub for pattern matching; you may
supply arguments as required (and therefore use
using the optional
Note that by default, grepl/gsub will use
fixed=FALSE, which means
new_value will be interepreted as regular
Chunking of text
Note that the behind-the-scenes representation of text in a Word document is frequently not what you might expect! Sometimes a paragraph of text is broken up (or "chunked") into several "runs," as a result of style changes, pauses in text entry, later revisions and edits, etc. If you have not styled the text, and have entered it in an "all-at-once" fashion, e.g. by pasting it or by outputing it programmatically into your Word document, then this will likely not be a problem. If you are working with a manually-edited document, however, this can lead to unexpected failures to find text.
You can use the officer function
show how the paragraph of text at the current cursor has been chunked into
runs, and what text is in each chunk. This can help troubleshoot unexpected
failures to find text.
body_replace_all_text( x, old_value, new_value, only_at_cursor = FALSE, warn = TRUE, ... ) headers_replace_all_text( x, old_value, new_value, only_at_cursor = FALSE, warn = TRUE, ... ) footers_replace_all_text( x, old_value, new_value, only_at_cursor = FALSE, warn = TRUE, ... )
a docx device
the value to replace
the value to replace it with
optional arguments to grepl/gsub (e.g.
Replacements will be performed in each header of all sections.
Replacements will be performed in each footer of all sections.
library(magrittr) doc <- read_docx() %>% body_add_par("Placeholder one") %>% body_add_par("Placeholder two") # Show text chunk at cursor docx_show_chunk(doc) # Output is 'Placeholder two'#>#># Simple search-and-replace at current cursor, with regex turned off doc <- body_replace_all_text(doc, old_value = "Placeholder", new_value = "new", only_at_cursor = TRUE, fixed = TRUE) docx_show_chunk(doc) # Output is 'new two'#>#># Do the same, but in the entire document and ignoring case doc <- body_replace_all_text(doc, old_value = "placeholder", new_value = "new", only_at_cursor=FALSE, ignore.case = TRUE) doc <- cursor_backward(doc) docx_show_chunk(doc) # Output is 'new one'#>#># Use regex : replace all words starting with "n" with the word "example" doc <- body_replace_all_text(doc, "\\bn.*?\\b", "example") docx_show_chunk(doc) # Output is 'example one'#>#>