在字符串中查找字符的位置

ric*_*rdo 81 regex string r

我想在字符串中找到一个字符的位置.

说: string = "the2quickbrownfoxeswere2tired"

我希望函数返回424- 2s 的字符位置string.

mne*_*nel 108

您可以使用 gregexpr

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


[[1]]
[1]  4 24
attr(,"match.length")
[1] 1 1
attr(,"useBytes")
[1] TRUE
Run Code Online (Sandbox Code Playgroud)

或者也许str_locate_all来自包装stringr的包装(从1.0版开始)gregexpr stringi::stri_locate_allstringr

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

[[1]]
     start end
[1,]     4   4
[2,]    24  24
Run Code Online (Sandbox Code Playgroud)

请注意,您可以简单地使用 stringi

library(stringi)
stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE)
Run Code Online (Sandbox Code Playgroud)

基地的另一个选择R是类似的

lapply(strsplit(x, ''), function(x) which(x == '2'))
Run Code Online (Sandbox Code Playgroud)

应该工作(给定一个字符向量x)


Jil*_*ina 35

这是另一种直截了当的选择.

> which(strsplit(string, "")[[1]]=="2")
[1]  4 24
Run Code Online (Sandbox Code Playgroud)


小智 17

你可以使用unlist使输出只有4和24:

unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired"))
[1]  4 24
Run Code Online (Sandbox Code Playgroud)