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


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


R 語言中的 grep() 函數用於在給定字符串的每個元素中搜索模式的匹配項。

用法: 
grep(pattern, x, ignore.case=TRUE/FALSE, value=TRUE/FALSE)
參數: 
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)

輸出:



[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




相關用法


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