Luke Birkett
Luke Birkett

Reputation: 13

Cut a string from right to left until a certain character is met R

I am looking to manipulate/cut a character string from right to left until a particular character is met

I want to take this: a <- "L1.L2.L3.L4.L5" And output this: a <- "L5"

I have specifically worded this problem as needing to cut the string from right to left because the strings can be of variable length and the output string can be of variable length as well

For example the code needs to work on:

b <- "L1.L555"

c <- "L1.L2.L3.L4.L5.L6.LLLL"

Upvotes: 1

Views: 327

Answers (1)

akrun
akrun

Reputation: 887711

We can use sub to match characters (.*) until a . (. is a metacharacter for any character. So we escape (\\) to evaluate it literally) and replace it with blank ("")

sub(".*\\.", "", a)
#[1] "L5"

sub(".*\\.", "", b)
#[1] "L555"

sub(".*\\.", "", c)
#[1] "LLLL"

Or using trimws

trimws(a, whitespace = ".*\\.")
#[1] "L5"

Upvotes: 1

Related Questions