简体   繁体   English

如何在R中的字符串末尾匹配子字符串?

[英]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

data 数据

v1 <- c("P6-B41A", "P6-B4")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R:如何使用 stringr 提取子字符串作为输出来变异以字符串模式开头并以数字结尾的字符串列? - 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? 如何在R中的字符串中查找重复元素(子字符串) - How to find repetitive elements(substring) in a string in R 如何从R中的字符串中查找子字符串? - How to find substring from string in R? 如何将表达式的开头和结尾与R中的grep进行匹配 - how to match the start and end of an expression with grep in R R 正则表达式提取 substring 后跟行尾或特定字符(惰性匹配) - R regex extract substring followed by end of line or specific character (lazy match) 如何在r中返回具有部分子字符串匹配的逻辑向量 - How to return a logical vector with a partial substring match in r r子字符串 - r substring string R正则表达式匹配字符串的开头和结尾,忽略中间 - R regex to match beginning and end of string, ignoring middle R中带有regexp的问题:匹配被空格或字符串开头/结尾包围的单词 - Troubles with regexp in R: Match word surrounded by whitespace or start/end of string 从具有固定的开始位置和结束点的字符串中提取R中的子字符串作为找到的字符 - Extract substring in R from string with fixed start position and end point as a character found
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM