當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


R語言 gsub()用法及代碼示例


gsub()R語言中的函數用於從字符串中替換一個模式的所有匹配項。如果未找到模式,則字符串將按原樣返回。

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

參數:
pattern:要匹配的字符串
replacement:替換字符串
string:字符串或字符串向量
忽略.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"

相關用法


注:本文由純淨天空篩選整理自nidhi_biet大神的英文原創作品 Replace all the matches of a Pattern from a String in R Programming – gsub() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。