如何确定字符串"是否以"结尾? R中的另一个字符串?

时间:2014-10-04 01:09:58

标签: r string ends-with

我想过滤掉在列的字符串值中包含'*'的表的行。只检查该列。

 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的第4个值应为TRUE。

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

另外,是否因为'*'作为字符而有问题,因为它意味着任何字符? grepl也没有用。

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

5 个答案:

答案 0 :(得分:8)

*是正则表达式中的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

答案 1 :(得分:8)

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

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

答案 2 :(得分:5)

我使用这样的东西:

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

答案 3 :(得分:1)

基础现在包含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)) == '*'快得多。

答案 4 :(得分:0)

这是一个整洁的解决方案:

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

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