[英]R: How to use stringr to extract the substring as the output to mutate a column of strings that begins with a string pattern and end with a number?
[英]How to match a substring at the end of a string in R?
我正在使用grepl来检测字符串是否包含子字符串。 例如:
grepl("-B4","P6-B4")
显然返回True。 现在,我要避免在“ -B4”子字符串之后包含字符的情况。 例如,我想从以下内容中查看False:
grepl("-B4","P6-B41A")
正如您所看到的,我要避免的原因是因为4与41不同,并且我不想检测41。谢谢
grepl("-B4$",c("P6-B41A", "P6-B4"))
#[1] FALSE TRUE
这似乎是使用endsWith()
的完美时机。 它确定字符串是否以特定字符或一系列字符结尾。
endsWith(c("P6-B41A", "P6-B4"), "-B4")
# [1] FALSE TRUE
并且根据help(endsWith)
,它也比grepl()
更有效。
另一种选择是提取最后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.