Reputation: 1008
Consider this data:
str <- c("OTB_MCD_100-119_0_0", "PS_SPF_16-31_0_0", "PP_DR/>16-77")
How to make it into a string like this?
str
[1] "OTB_MCD" "PS_SPF" "PP_DR"
I tried substr, but it doesn't work when the characters are of different length.
Upvotes: 1
Views: 55
Reputation: 887981
We can use sub
to match zero or more _
followed by 0 or more characters that are not alphabets ([^A-Za-z]*
) until the end ($
) of the string, replace it with blank (""
)
sub("_*[^A-Za-z]*$", "", str)
#[1] "OTB_MCD" "PS_SPF" "PP_DR"
Upvotes: 2