【问题标题】:Replace all characters, except the first, in every word of a string with lowercase用小写替换字符串中每个单词中除第一个字符外的所有字符
【发布时间】:2018-05-18 03:15:26
【问题描述】:

我有一个字符串

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

【问题讨论】:

  • 例如,您可以使用lookbehind。

标签: r regex replace gsub tolower


【解决方案1】:

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

【讨论】:

  • 真漂亮,谢谢!!我想我会借此机会询问您是否碰巧知道一个在线资源,其中包含 R 中的正则表达式语法的完整列表。
  • 任何好的正则表达式资源都可以帮助您使用 R 正则表达式。实际上,Stack Overflow 是一个很好的资源。
【解决方案2】:

但是应该有一些漂亮的方法来做到这一点,一种方法是拆分每个单词并降低除第一个单词之外的单词的所有字符,然后将 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."

【讨论】:

  • 我刚刚收到了令人讨厌的反对票。我已经颠倒了你的,并会要求你也这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
  • 2019-08-08
  • 1970-01-01
  • 2018-05-28
相关资源
最近更新 更多