将字符串的每个单词中除第一个字符外的所有字符替换为小写

Replace all characters, except the first, in every word of a string with lowercase

我有一个字符串

text <- "This String IS a tESt. TRYING TO fINd a waY to do ThiS."

并且我想在 R 中使用 gsub 将每个单词中不是第一个字母的所有字符替换为小写。这可能吗?

desired_output <- "This String Is a test. Trying To find a way to do This."

应该有一些漂亮的方法来做到这一点,但是,一种方法是拆分每个单词并降低单词的所有字符,除了第一个字符,然后 paste 字符串返回。

paste0(sapply(strsplit(text, " ")[[1]], function(x) 
 paste0(substr(x, 1, 1),tolower(substr(x, 2, nchar(x))))), collapse = " ")

#[1] "This String Is a test. Trying To find a way to do This."

详细的步骤说明:

strsplit(text, " ")[[1]]

#[1] "This"   "String" "IS"     "a"      "tESt."  "TRYING" "TO"     "fINd"  
# [9] "a"      "waY"    "to"     "do"     "ThiS." 

sapply(strsplit(text, " ")[[1]], function(x) 
         paste0(substr(x, 1, 1),tolower(substr(x, 2, nchar(x)))))

#   This   String       IS        a    tESt.   TRYING       TO     fINd 
#  "This" "String"     "Is"      "a"  "test." "Trying"     "To"   "find" 
#       a      waY       to       do    ThiS. 
#     "a"    "way"     "to"     "do"  "This." 


paste0(sapply(strsplit(text, " ")[[1]], function(x) 
  paste0(substr(x, 1, 1),tolower(substr(x, 2, nchar(x))))), collapse = " ")

#[1] "This String Is a test. Trying To find a way to do This."

有一个很好的方法可以做到这一点。我们可以在 Perl 模式下调用 gsub,利用小写捕获组的能力。

text <- "This String IS a tESt. TRYING TO fINd a waY to do ThiS."
gsub("(?<=\b.)(.*?)\b", "\L\1", text, perl=TRUE)

[1] "This String Is a test. Trying To find a way to do This."

Demo