[英]How to match a substring at the end of a string in R?
I'm using grepl to detect if a string includes a substring. 我正在使用grepl来检测字符串是否包含子字符串。 For example:
例如:
grepl("-B4","P6-B4")
which obviously returns True. 显然返回True。 Now I want to avoid cases which have characters after the "-B4" substring.
现在,我要避免在“ -B4”子字符串之后包含字符的情况。 For example I want to see False from the following:
例如,我想从以下内容中查看False:
grepl("-B4","P6-B41A")
As you can see the reason I want to avoid it is because 4 is different from 41 and I don't want to detect 41. Thanks 正如您所看到的,我要避免的原因是因为4与41不同,并且我不想检测41。谢谢
grepl("-B4$",c("P6-B41A", "P6-B4"))
#[1] FALSE TRUE
This seems like the perfect time to use endsWith()
. 这似乎是使用
endsWith()
的完美时机。 It determines if a string ends with a specific character or series of characters. 它确定字符串是否以特定字符或一系列字符结尾。
endsWith(c("P6-B41A", "P6-B4"), "-B4")
# [1] FALSE TRUE
And according to help(endsWith)
, it's also more efficient than grepl()
. 并且根据
help(endsWith)
,它也比grepl()
更有效。
Another option would be to extract the last 3 characters and do a ==
另一种选择是提取最后3个字符并执行
==
substr(v1, nchar(v1)-2, nchar(v1)) == "-B4"
#[1] FALSE TRUE
v1 <- c("P6-B41A", "P6-B4")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.