在 R 编程中查找匹配模式在字符串中的位置 – grep()函数
R 语言中的grep()函数用于在给定字符串的每个元素中搜索模式的匹配项。
Syntax:
grep(pattern, x, ignore.case=TRUE/FALSE, value=TRUE/FALSE)
Parameters:
pattern: Specified pattern which is going to be matched with given elements of the string.
x: Specified string vector.
ignore.case: If its value is TRUE, it ignores case.
value: If its value is TRUE, it return the matching elements vector, else return the indices vector.
示例 1:
Python3
# R program to illustrate
# grep function
# Creating string vector
x <- c("GFG", "gfg", "Geeks", "GEEKS")
# Calling grep() function
grep("gfg", x)
grep("Geeks", x)
grep("gfg", x, ignore.case = FALSE)
grep("Geeks", x, ignore.case = TRUE)
Python3
# R program to illustrate
# grep function
# Creating string vector
x <- c("GFG", "gfg", "Geeks", "GEEKS")
# Calling grep() function
grep("gfg", x, ignore.case = TRUE, value = TRUE)
grep("G", x, ignore.case = TRUE, value = TRUE)
grep("Geeks", x, ignore.case = FALSE, value = FALSE)
grep("GEEKS", x, ignore.case = FALSE, value = FALSE)
输出 :
[1] 2
[1] 3
[1] 2
[1] 3 4
示例 2:
Python3
# R program to illustrate
# grep function
# Creating string vector
x <- c("GFG", "gfg", "Geeks", "GEEKS")
# Calling grep() function
grep("gfg", x, ignore.case = TRUE, value = TRUE)
grep("G", x, ignore.case = TRUE, value = TRUE)
grep("Geeks", x, ignore.case = FALSE, value = FALSE)
grep("GEEKS", x, ignore.case = FALSE, value = FALSE)
输出:
[1] "GFG" "gfg"
[1] "GFG" "gfg" "Geeks" "GEEKS"
[1] 3
[1] 4