Achal Neupane
Achal Neupane

Reputation: 5719

How to remove start and end of the string in R?

I have this string mystring. I want to remove the begining and end of the string in one go and get the result. How do I do this ?

mystring <- c("new_DCLd_2_LTR_assembly.csv", "new_nonLTR_DCLd_2_assembly.csv"
)

result I want:

DCLd_2_LTR_assembly nonLTR_DCLd_2_assembly

Upvotes: 0

Views: 1685

Answers (2)

BENY
BENY

Reputation: 323226

library(stringr) 
str_sub(mystring,5,-5)
[1] "DCLd_2_LTR_assembly"    "nonLTR_DCLd_2_assembly"

Or just using (As per akrun )

substr(mystring, 5, nchar(mystring)-4)

Upvotes: 2

akrun
akrun

Reputation: 887068

We can use gsub to match zero or more character that are not a _ ([^_]*) followed by a _ from the start (^) of the string or (|) the . followed by csv and replace it with blank ("")

gsub("^[^_]*_|\\.csv", "", mystring)
#[1] "DCLd_2_LTR_assembly"    "nonLTR_DCLd_2_assembly"

Or use sub with capture groups

sub("^[^_]*_([^.]*)\\..*", "\\1", mystring)

Upvotes: 3

Related Questions