![](/img/trans.png)
[英]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.