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

时间:2018-05-18 03:15:27

标签: r regex replace gsub tolower

我有一个字符串

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."

2 个答案:

答案 0 :(得分:2)

有一种很好的方法可以做到这一点。我们可以在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

答案 1 :(得分:0)

应该有一些很好的方法可以做到这一点,但是,一种方法是分割每个单词并降低除第一个单词之外的单词的所有字符,然后再将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."
相关问题