且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字符串向量转换为标题大小写

更新时间:2023-02-15 19:30:57

主要问题是您缺少 perl=TRUE(并且您的正则表达式略有错误,尽管这可能是结果试图解决第一个问题).

The main problem is that you're missing perl=TRUE (and your regex is slightly wrong, although that may be a result of flailing around to try to fix the first problem).

使用 [:lower:] 而不是 [az] 稍微安全一些,以防您的代码最终以某种奇怪的方式运行 (抱歉,爱沙尼亚人) 语言环境,其中 z 不是最后一个字母字母表...

Using [:lower:] instead of [a-z] is slightly safer in case your code ends up being run in some weird (sorry, Estonians) locale where z is not the last letter of the alphabet ...

re_from <- "\\b([[:lower:]])([[:lower:]]+)"
strings <- c("first phrase", "another phrase to convert",
             "and here's another one", "last-one")
gsub(re_from, "\\U\\1\\L\\2" ,strings, perl=TRUE)
## [1] "First Phrase"              "Another Phrase To Convert"
## [3] "And Here's Another One"    "Last-One"    

您可能更喜欢使用 \\E(停止大写)而不是 \\L(开始小写),具体取决于您要遵循的规则,例如:

You may prefer to use \\E (stop capitalization) rather than \\L (start lowercase), depending on what rules you want to follow, e.g.:

string2 <- "using AIC for model selection"
gsub(re_from, "\\U\\1\\E\\2" ,string2, perl=TRUE)
## [1] "Using AIC For Model Selection"