【问题标题】:Find the location of a character in string查找字符串中字符的位置
【发布时间】:2012-12-24 08:19:34
【问题描述】:

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

说:string = "the2quickbrownfoxeswere2tired"

我希望函数返回424——2s 在string 中的字符位置。

【问题讨论】:

  • 为什么要使用正则表达式? r 没有.indexOf() 什么的吗?
  • 我对此表示怀疑。开发人员是 Nixers,并假设每个人都知道正则表达式。 R 的字符串处理有点笨拙。

标签: regex string r


【解决方案1】:

您可以使用gregexpr

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


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

或者可能来自包 stringrstr_locate_all,它是 gregexpr stringi::stri_locate_all 的包装器(截至 stringr 1.0 版)

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

【讨论】:

  • 我们如何从您的前 3 个解决方案返回的列表/对象中提取整数?
  • 使用regexpr 而不是gregexpr 可以轻松获取整数。或者在输出上使用unlist,如下面的另一个答案所示。
【解决方案2】:

这是另一种直接的选择。

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

【讨论】:

  • 你能解释一下[[1]] 的作用吗?
  • @francoiskroll, [[1]] 表示列表的第一个元素。
【解决方案3】:

您可以使用 unlist 将输出设为 4 和 24:

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

【讨论】:

    【解决方案4】:

    在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
    

    【讨论】:

      【解决方案5】:

      要仅查找第一个位置,请使用lapply()min()

      my_string <- c("test1", "test1test1", "test1test1test1")
      
      unlist(lapply(gregexpr(pattern = '1', my_string), min))
      #> [1] 5 5 5
      
      # or the readable tidyverse form
      my_string %>%
        gregexpr(pattern = '1') %>%
        lapply(min) %>%
        unlist()
      #> [1] 5 5 5
      

      要仅查找最后个位置,请使用lapply()max()

      unlist(lapply(gregexpr(pattern = '1', my_string), max))
      #> [1]  5 10 15
      
      # or the readable tidyverse form
      my_string %>%
        gregexpr(pattern = '1') %>%
        lapply(max) %>%
        unlist()
      #> [1]  5 10 15
      

      【讨论】:

        【解决方案6】:

        你也可以使用grep

        grep('2', strsplit(string, '')[[1]])
        #4 24
        

        【讨论】:

          猜你喜欢
          • 2012-05-21
          • 2016-06-10
          • 2012-08-03
          • 1970-01-01
          • 1970-01-01
          • 2017-03-27
          相关资源
          最近更新 更多