Using the Justin approach, I developed the following:
beg2char <- function(text, char = " ", noc = 1, include = FALSE) { inc <- ifelse(include, char, "?") specchar <- c(".", "|", "(", ")", "[", "{", "^", "$", "*", "+", "?") if(char %in% specchar) { char <- paste0("\\", char) } ins <- paste(rep(paste0(char, ".+"), noc - 1), collapse="") rep <- paste0("^(.+", ins, inc, ").*$") gsub(rep, "\\1", text) } x <- c("a_b_c_d", "1_2_3_4", "<_?_._:") beg2char(x, "_", 1) beg2char(x, "_", 2) beg2char(x, "_", 3) beg2char(x, "_", 4) beg2char(x, "_", 3, include=TRUE)
source share