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

StackOverflow https://stackoverflow.com/questions/21998947

سؤال

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"
هل كانت مفيدة؟

المحلول

Try this:

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

or this:

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

نصائح أخرى

Use \\L or \\U to change the case in the replacement argument. You can use \\E to end the effect of the case conversion.

gsub(x=test,pattern="-(\\w)",replacement="\\L\\1", perl=TRUE)
# [1] "Kwak Minjung"
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top