【问题标题】:How to determine if a string "ends with" another string in R?如何确定一个字符串是否以 R 中的另一个字符串“结尾”?
【发布时间】:2014-10-04 01:09:57
【问题描述】:

我想过滤掉列的字符串值中包含“*”的表的行。仅检查该列。

 string_name = c("aaaaa", "bbbbb", "ccccc", "dddd*", "eee*eee")

 zz <- sapply(tx$variant_full_name, function(x) {substrRight(x, -1) =="*"})
 Error in FUN(c("Agno I30N", "VP2 E17Q", "VP2 I204*", "VP3 I85F", "VP1 K73R",  : 
   could not find function "substrRight"

这样,zz 的第四个值应该是 TRUE。

在python中有用于字符串的endswith函数[ string_s.endswith('*') ] R中是否有类似的东西?

另外,因为 '*' 作为一个字符,它意味着任何字符,这是否有问题? grepl 也不起作用。

> grepl("*^",'dddd*')
[1] TRUE
> grepl("*^",'dddd')
[1] TRUE

【问题讨论】:

  • 你可以转义*grepl("\\*",'dddd*')。要查找以* 结尾的字符串,您可以使用grepl("\\*$", string_name)

标签: r string ends-with


【解决方案1】:

Base 现在包含 startsWithendsWith。因此,OP 的问题可以用endsWith 来回答:

> string_name = c("aaaaa", "bbbbb", "ccccc", "dddd*", "eee*eee")
> endsWith(string_name, '*')
[1] FALSE FALSE FALSE  TRUE FALSE

这比substring(string_name, nchar(string_name)) == '*' 快得多。

【讨论】:

    【解决方案2】:

    * 是正则表达式中的quantifier。它告诉正则表达式引擎尝试匹配前面的标记“零次或多次”。要匹配文字,您需要在其前面加上两个反斜杠或放在字符类 [*] 内。要检查字符串是否以特定模式结尾,请使用end of string $ anchor

    > grepl('\\*$', c('aaaaa', 'bbbbb', 'ccccc', 'dddd*', 'eee*eee'))
    # [1] FALSE FALSE FALSE  TRUE FALSE
    

    您可以简单地做到这一点,而无需在基础 R 中实现正则表达式:

    > x <- c('aaaaa', 'bbbbb', 'ccccc', 'dddd*', 'eee*eee')
    > substr(x, nchar(x)-1+1, nchar(x)) == '*'
    # [1] FALSE FALSE FALSE  TRUE FALSE
    

    【讨论】:

      【解决方案3】:

      这很简单,您不需要正则表达式。

      > string_name = c("aaaaa", "bbbbb", "ccccc", "dddd*", "eee*eee")
      > substring(string_name, nchar(string_name)) == "*"
      [1] FALSE FALSE FALSE  TRUE FALSE
      

      【讨论】:

        【解决方案4】:

        我使用这样的东西:

        strEndsWith <- function(haystack, needle)
        {
          hl <- nchar(haystack)
          nl <- nchar(needle)
          if(nl>hl)
          {
            return(F)
          } else
          {
            return(substr(haystack, hl-nl+1, hl) == needle)
          }
        }
        

        【讨论】:

          【解决方案5】:

          这是一个 tidyverse 解决方案:

          string_name = c("aaaaa", "bbbbb", "ccccc", "dddd*", "eee*eee")
          str_sub(string_name, -1) == "*"
          [1] FALSE FALSE FALSE  TRUE FALSE
          

          它的优点是可读性更强,如果需要检查不同的位置,也可以轻松更改。

          【讨论】:

          • 您能否把它变成一个可重复的答案,应用于这个问题?
          猜你喜欢
          • 1970-01-01
          • 2014-02-09
          • 1970-01-01
          • 1970-01-01
          • 2020-01-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-06
          相关资源
          最近更新 更多