str <- 'This is a _string with_ some _random underscores_ in it.' gsub("_+([[:print:]]+?)_+", "\\1", str) str <- 'This is a _random string with_ a scale of 1_10.' gsub("_+([[:print:]]+?)_+", "\\1", str)
Standard input is empty
[1] "This is a string with some random underscores in it." [1] "This is a random string with a scale of 1_10."