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

Replace markdown bold syntax with latex code

I am struggling to construct the correct regex expression to replace markdown bold syntax (double stars) with LaTeX code using the stringr::str_replace_all() function.

For example, I have the string "**first chunk** not bold, and **bold again**", and I would like to convert it to "\textbf{first chunk} not bold, and \textbf{bold again}".

stringr::str_replace_all(
  "**first chunk** not bold, and **bold again**",
  pattern = "\\*\\*.*\\*\\*", # this probably needs to be updated 
  replacement = <what goes here?>
)
#> "\textbf{first chunk} not bold, and \textbf{bold again}"

Thank you

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

>Solution :

Use capture groups:

library(stringr)

str_replace_all(
  "**first chunk** not bold, and **bold again**",
  pattern = "\\*\\*(.*?)\\*\\*",
  replacement = "\\\\textbf{\\1}"
)

[1] "\\textbf{first chunk} not bold, and \\textbf{bold again}"
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