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

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

[1] "R Tutorial"       "Java example"     "Go-Lang Tutorial"
[1] "R Tutorial"       "Java Tutorial"    "Go-Lang Tutorial"
My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.