2013-01-10 110 views
56

我想查找字符串中字符的位置。在字符串中查找字符的位置

說:string = "the2quickbrownfoxeswere2tired"

我想函數返回424 - 在string2 S的字符位置。

+0

爲什麼使用正則表達式?沒有'.indexOf()'或者什麼的? – fge

+0

我對此表示懷疑。開發人員是Nixers,並假定每個人都知道正則表達式。 R的字符串處理是一種混亂。 –

回答

79

您可以使用gregexpr

gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired") 


[[1]] 
[1] 4 24 
attr(,"match.length") 
[1] 1 1 
attr(,"useBytes") 
[1] TRUE 

或者是從包stringrstr_locate_all這是gregexprstringi::stri_locate_all的包裝(如1.0 stringr版)

library(stringr) 
str_locate_all(pattern ='2', "the2quickbrownfoxeswere2tired") 

[[1]] 
    start end 
[1,]  4 4 
[2,] 24 24 

注意,你可以簡單地使用stringi

library(stringi) 
stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE) 

在基地R另一種辦法是像

lapply(strsplit(x, ''), function(x) which(x == '2')) 

應該工作(給定一個字符向量x

+0

我們如何從前3個解決方案返回的列表/對象中提取整數? –

26

這裏還有一個簡單的選擇。

> which(strsplit(string, "")[[1]]=="2") 
[1] 4 24 
10

您只需4和24使用不公開使輸出:

unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired")) 
[1] 4 24 
0

發現STR2在STR1的第n次出現(順序相同的參數,如Oracle SQL INSTR)的位置,返回0如果找不到

instr <- function(str1,str2,startpos=1,n=1){ 
    aa=unlist(strsplit(substring(str1,startpos),str2)) 
    if(length(aa) < n+1) return(0); 
    return(sum(nchar(aa[1:n])) + startpos+(n-1)*nchar(str2)) 
} 


instr('xxabcdefabdddfabx','ab') 
[1] 3 
instr('xxabcdefabdddfabx','ab',1,3) 
[1] 15 
instr('xxabcdefabdddfabx','xx',2,1) 
[1] 0