Marcin
Marcin

Reputation: 8074

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.

But unfortunately it does work. Can anyone help me? Below is my code.

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

Upvotes: 0

Views: 2166

Answers (3)

hwnd
hwnd

Reputation: 70750

You can avoid using regular expression and use substr to do this.

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

Or use str_sub from the stringr package:

> str_sub(x, -1) == '/'
[1] TRUE

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174874

You could use a simple grepl function,

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

Upvotes: 2

vks
vks

Reputation: 67988

^.*\/$

You can use this.This will fail if last character is not /.

Upvotes: 1

Related Questions