简体   繁体   English

使用regexpr函数查找R中的最后一个字符

[英]Finding last character in R using regexpr function

I am having problem with finding the last character in a string. 我在查找字符串中的最后一个字符时遇到问题。 I am trying to use the regexpr function to check if the last character is equal to / forward slash. 我正在尝试使用regexpr函数来检查最后一个字符是否等于/正斜杠。

But unfortunately it does work. 但不幸的是它确实起作用。 Can anyone help me? 谁能帮我? Below is my code. 下面是我的代码。

regexpr( pattern = ".$", text = /home/rexamine/archivist2/ex/// ) != "/"

You can avoid using regular expression and use substr to do this. 您可以避免使用正则表达式,而使用substr可以做到这一点。

> x <- '/home/rexamine/archivist2/ex///'
> substr(x, nchar(x)-1+1, nchar(x)) == '/'
[1] TRUE

Or use str_sub from the stringr package: 或使用str_substringr包:

> str_sub(x, -1) == '/'
[1] TRUE
^.*\/$

您可以使用它。如果最后一个字符不是/这将失败。

You could use a simple grepl function, 您可以使用一个简单的grepl函数,

> text = "/home/rexamine/archivist2/ex///"
> grepl("/$", text, perl=TRUE)
[1] TRUE
> text = "/home/rexamine/archivist2/ex"
> grepl("/$", text, perl=TRUE)
[1] FALSE

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM