13

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

 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
4

5 回答 5

15

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)) == '*'.

于 2019-05-17T09:59:39.247 回答
13

*是正则表达式中的量词。它告诉正则表达式引擎尝试匹配前面的标记“零次或多次”。要匹配文字,您需要在其前面加上两个反斜杠或放置在字符类[*]中。要检查字符串是否以特定模式结尾,请使用字符串的结尾$ 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
于 2014-10-04T01:14:47.967 回答
8

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

> string_name = c("aaaaa", "bbbbb", "ccccc", "dddd*", "eee*eee")
> substring(string_name, nchar(string_name)) == "*"
[1] FALSE FALSE FALSE  TRUE FALSE
于 2014-10-04T02:19:30.287 回答
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)
  }
}
于 2015-04-22T05:47:24.390 回答
0

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

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

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

于 2020-07-09T16:37:46.247 回答