如何确定一个字符串"以"结束于R中的另一个字符串?

Mal*_*aya 10 string r 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"
Run Code Online (Sandbox Code Playgroud)

由此,zz的第4个值应该为TRUE.

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

此外,它是否有问题,因为'*'作为一个字符,因为它意味着任何字符?grepl也没有用.

> grepl("*^",'dddd*')
[1] TRUE
> grepl("*^",'dddd')
[1] TRUE
Run Code Online (Sandbox Code Playgroud)

Vid*_*a G 9

Base 现在包含startsWithendsWith。因此 OP 的问题可以用以下方式回答endsWith

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

这比substring(string_name, nchar(string_name)) == '*'.


hwn*_*wnd 8

*是正则表达式中的量词.它告诉正则表达式引擎尝试匹配前面的标记"零次或多次".要匹配文字,您需要在其前面加上两个反斜杠或放在字符类中[*].要检查字符串是否以特定模式结束$ ,请使用字符串锚点结束.

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

您可以在不在基数R中实现正则表达式的情况下执行此操作:

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


Hon*_*Ooi 8

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

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


kro*_*dil 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)
  }
}
Run Code Online (Sandbox Code Playgroud)