📜  在 R 编程中从字符串中替换模式的所有匹配项 – gsub()函数

📅  最后修改于: 2022-05-13 01:54:25.308000             🧑  作者: Mango

在 R 编程中从字符串中替换模式的所有匹配项 – gsub()函数

R 语言中的gsub()函数用于替换字符串中模式的所有匹配项。如果未找到该模式,则字符串将按原样返回。

示例 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"