Search code examples
regexrsubstitutionlowercase

How to substitute a letter with its lowercase after finding it through regex match in R


I have a bunch of strings with a hyphen in it. I want to remove the hyphen and convert the following letter to lower case while keeping all the other letters intact. How do you accomplish task in R?

test <- "Kwak Min-Jung"
gsub(x=test,pattern="-(\\w)",replacement="\\1")
# [1] "Kwak MinJung"  , Not what I want
# I want it to convert to  "Kwak Minjung"

Solution

  • Try this:

    > gsub("-(\\w)", "\\L\\1", test, perl = TRUE)
    [1] "Kwak Minjung"
    

    or this:

    > library(gsubfn)
    > gsubfn("-(\\w)", tolower, test)
    [1] "Kwak Minjung"