lokheart
lokheart

Reputation: 24675

converting case on selected alphabet in R using gsub

I have a string that I need to convert it into pre-specified case format:

CHAN TAI MAN needs to be converted to CHAN Tai Man

The string is actually a chinese name. I know how to capture the AI and AN in my case using the following regex command in R:

^[A-Z]+ [A-Z]([A-Z]+) [A-Z]([A-Z]+) can pick up the AI and AN for me, but I don't know how to use regex to conver them to lower case.

How can it be done?

Upvotes: 1

Views: 91

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

Here's a solution using sub:

s <- "CHAN TAI MAN"

sub("(\\w+ \\w)(\\w+)( \\w)(\\w+)", "\\1\\L\\2\\U\\3\\L\\4", s, perl = TRUE)
# [1] "CHAN Tai Man"

Here, \\L means lowercase, and \\U means uppercase.

Upvotes: 1

Related Questions