data_string <- "Substring removing"
# $ 把匹配限定在末尾
no_suffix <- sub(" removing$", "", data_string)
# no_suffix = Substring
# ^ 把匹配限定在开头
no_prefix <- sub("^Sub", "", no_suffix)
# no_prefix = string
# 从中间删除
marked <- "Substring removing!"
middle <- sub(" removing", "", marked,
fixed = TRUE)
# middle = Substring!
# 不加 $ 时,被删除的是第一处匹配,而不是最后一处
text <- "x removing y removing"
first_gone <- sub(" removing", "", text,
fixed = TRUE)
# first_gone = x y removing
last_gone <- sub(" removing$", "", text)
# last_gone = x removing y
# gsub() 删除所有匹配项
all_gone <- gsub(" removing", "", text,
fixed = TRUE)
# all_gone = x y
cat("no_suffix =", no_suffix, "\n")
cat("no_prefix =", no_prefix, "\n")
cat("middle =", middle, "\n")
cat("first_gone =", first_gone, "\n")
cat("last_gone =", last_gone, "\n")
cat("all_gone =", all_gone, "\n")