如何确定一个字符串是否以“结尾". R中的另一个字符串? [英] How to determine if a string "ends with" another string in R?

查看:481
本文介绍了如何确定一个字符串是否以“结尾". R中的另一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想过滤出表的行,该表的行的字符串值中包含"*".仅检查该列.

I want to filter out the rows of a table which contain '*' in the string value of the column. Checking just that column.

 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.

The 4th value of zz should be TRUE by this.

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

in python there is endswith function for strings [ string_s.endswith('*') ] Is there something similar to that in R ?

还因为"*"作为一个字符而存在问题,因为它表示任何字符吗? grepl也无法正常工作.

Also, is it problem because of '*' as a character as it means any character ? grepl also not working.

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

推荐答案

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

* is a quantifier in regular expressions. It tells the regular expression engine to attempt to match the preceding token "zero or more times". To match a literal, you need to precede it with two backslashes or place inside of a character class [*]. To check if the string ends with a specific pattern, use the end of string $ anchor.

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

您可以简单地执行此操作,而无需在基数R中实现正则表达式:

You can simply do this without implementing a regular expression in base R:

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

这篇关于如何确定一个字符串是否以“结尾". R中的另一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆