Open In App

Replace all the matches of a Pattern from a String in R Programming – gsub() Function

Improve
Improve
Like Article
Like
Save
Share
Report

gsub() function in R Language is used to replace all the matches of a pattern from a string. If the pattern is not found the string will be returned as it is.

Syntax:
gsub(pattern, replacement, string, ignore.case=TRUE/FALSE)

Parameters:
pattern: string to be matched
replacement: string for replacement
string: String or String vector
ignore.case: Boolean value for case-sensitive replacement

Example 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)


Output:

[1] "Goodsforgoods"
[1] "GeeksforBooks"
[1] "BooksforBooks"

Example 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)


Output:

[1] "R Tutorial"       "Java example"     "Go-Lang Tutorial"
[1] "R Tutorial"       "Java Tutorial"    "Go-Lang Tutorial"


Last Updated : 05 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads