2013-01-10 22 views
56

文字列内の文字の位置を探したい。文字列内の文字の位置を見つける

セイ:string = "the2quickbrownfoxeswere2tired"

私は424を返すために機能をしたいと思います - string2 Sの文字の位置を。

+0

なぜ正規表現を使用しますか? rに '.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 

か、単に使用することができ

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

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

ノート(stringrバージョン1.0のような)gregexprstringi::stri_locate_allのラッパーがあるパッケージstringrから多分str_locate_allstringi

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

はSTR1でSTR2の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 
関連する問題