I'm using grepl to detect if a string includes a substring. For example:
grepl("-B4","P6-B4")
which obviously returns True. Now I want to avoid cases which have characters after the "-B4" substring. For example I want to see False from the following:
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
grepl("-B4$",c("P6-B41A", "P6-B4"))
#[1] FALSE TRUE
This seems like the perfect time to use 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()
.
Another option would be to extract the last 3 characters and do a ==
substr(v1, nchar(v1)-2, nchar(v1)) == "-B4"
#[1] FALSE TRUE
v1 <- c("P6-B41A", "P6-B4")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.