Remove the last few capital letters on R

Viewed 183

I was wondering how I could remove the last few capital letters and symbol "/" of each observation string in R? For example, if I have data like

    PlayerFirstLastNameABC
    PlayerNameAB/CDF
    PlayerFirstMN
    PlayerLastNameABC/RS

and so on, how do I get it to return to me:

    PlayerFirstLastName
    PlayerName
    PlayerFirst
    PlayerLastName

where the last letter of the string is always a lower case letter? i.e. Remove all end of strings until you hit a lower case letter. Thanks!

2 Answers

We can use sub from base R to match one or more (+) upper case letters along with / till the end ($) of the string and replace with blank ("")

sub("[A-Z/]+$", "", v1)
#[1] "PlayerFirstLastName" "PlayerName"         
#[3] "PlayerFirst"         "PlayerLastName"  

Or using trimws

trimws(v1, whitespace = "[A-Z/]+", which = "right")
#[1] "PlayerFirstLastName" "PlayerName"       
#[3]   "PlayerFirst"         "PlayerLastName"      

data

v1 <- c("PlayerFirstLastNameABC", "PlayerNameAB/CDF", "PlayerFirstMN", 
"PlayerLastNameABC/RS")

You can capture everything until upper case letters and / at the end of the string.

sub('(.*?)[/A-Z]+$', '\\1', x)
#[1] "PlayerFirstLastName" "PlayerName"  "PlayerFirst"  "PlayerLastName"
Related