R语言 替换一个字符串中所有匹配的模式 – gsub()函数
R语言中的 gsub() 函数用于替换一个字符串中的所有匹配模式。如果没有找到该模式,将返回字符串的原貌。
语法:
gsub(pattern, replacement, string, ignore.case=TRUE/FALSE)
参数:
pattern: 要匹配的字符串
replacement: 用于替换的字符串
string: 字符串或字符串向量
ignore.case: 用于区分大小写替换的布尔值
例子1 :
# R program to illustrate
# the use of gsub() function
# Create a string
x <- "Geeksforgeeks"
# Calling gsub() function
gsub("eek", "ood", x)
# Calling gsub() with case-sensitivity
gsub("gee", "Boo", x, ignore.case = FALSE)
# Calling gsub() with case-insensitivity
gsub("gee", "Boo", x, ignore.case = TRUE)
输出
[1] "Goodsforgoods"
[1] "GeeksforBooks"
[1] "BooksforBooks"
例2 :
# R program to illustrate
# the use of gsub() function
# Create a string
x <- c("R Example", "Java example", "Go-Lang Example")
# Calling gsub() function
gsub("Example", "Tutorial", x)
# Calling gsub() with case-insensitivity
gsub("Example", "Tutorial", x, ignore.case = TRUE)
输出
[1] "R Tutorial" "Java example" "Go-Lang Tutorial"
[1] "R Tutorial" "Java Tutorial" "Go-Lang Tutorial"