在 R 编程中从字符串中替换模式的第一个匹配项 – sub()函数
R 语言中的sub
函数用于替换字符串中模式的第一个匹配项。如果存在字符串元素的向量,则它将替换所有元素中模式的第一个匹配项。
Syntax: sub(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
示例 1:
# R program to illustrate
# the use of sub() function
# Create a string
x <- "Geeksforgeeks"
# Calling sub() function
sub("eek", "ood", x)
# Calling sub() with case-sensitivity
sub("gee", "Boo", x, ignore.case = FALSE)
# Calling sub() with case-insensitivity
sub("gee", "Boo", x, ignore.case = TRUE)
输出:
[1] "Goodsforgeeks"
[1] "GeeksforBooks"
[1] "Booksforgeeks"
示例 2:
# R program to illustrate
# the use of sub() function
# Create a string
x <- c("Geekforgeek", "Geeksforgeeks", "geeksforGeeks")
# Calling sub() function
sub("Gee", "boo", x)
# Calling sub() with case-insensitivity
sub("Gee", "boo", x, ignore.case = TRUE)
输出:
[1] "bookforgeek" "booksforgeeks" "geeksforbooks"
[1] "bookforgeek" "booksforgeeks" "booksforGeeks"