Henk
Henk

Reputation: 3656

get last part of a string

I would like to get the last substring of a variable (the last part after the underscore), in this case: "myvar".

x = "string__subvar1__subvar2__subvar3__myvar"

my attempts result in a match starting from the first substring, e.g.

library(stringr)
str_extract(x, "__.*?$)

How do I do this in R?

Upvotes: 1

Views: 1393

Answers (3)

PKumar
PKumar

Reputation: 11128

You can do:

library(stringr)
str_extract(x,"[a-zA-Z]+$")

EDIT: one could use lookaround feature as well: str_extract(x,"(?=_*)[a-zA-Z]+$")

also from baseR

regmatches(x,gregexpr("[a-zA-Z]+$",x))[[1]]

From documentation ?regex:

The caret ^ and the dollar sign $ are metacharacters that respectively match the empty string at the beginning and end of a line.

Upvotes: 3

kostr
kostr

Reputation: 856

Could this work? Sorry, I hope i'm understanding what you're asking correctly.

substr(x,gregexpr("_",x)[[1]][length(gregexpr("_",x)[[1]])]+1,nchar(x))
[1] "myvar"

Upvotes: 1

user2510479
user2510479

Reputation: 1540

You can do

sub('.*\\__', '', x)

Upvotes: 6

Related Questions