如何在首字母缩写大写的同时仅将每个单词的首字母大写?

我正在编写一个自动执行变量名清除的函数,以生成同质的变量名。通常将类似“ This is anExample”的内容转换为“ This.Is.An.Example”。通常,所有这些操作都非常容易,但是对于包含在变量名中的首字母缩略词,我遇到了麻烦。

一个例子是:“时间PST”最好变成“ Clock.In.Time.PST”

我曾尝试将str_to_upper修改为一个函数,但是我对C的使用并不了解,而C似乎是编写stringi的背景。

我唯一的下一个想法是对字符串是否没有空格或标点进行条件检查,然后在前一个字母为小写的情况下在大写字母之前插入空格。那是我唯一真正的想法,那就是如何处理它。

Example<-c("Easy Example Test","Medium..example TEst","HaRd exampleTEST","Truly HARd TestCase  PST")


#Step 1 - Removes all punctuation replacing with spaces
Example<-stringr::str_replace_all(Example,"[[:punct:]]"," ")

#Step 2 - This inserts a space wherever an uppercase letter is found with a preceding lowercase letter.
Example<-stringr::str_replace_all(Example,"([[:lower:]](?=[[:upper:]])|[[:upper:]](?=[[:upper:]][[:lower:]]))","\\1 ")

#Step 3 - This replaces all consecutive spaces with a period
Example<-stringr::str_replace_all(names(df),"\\s{1,}",".")





Current.Outcome<-c("Easy.Example.Test","Medium.example.T.Est","Ha.Rd.example.TEST","Truly.HA.Rd.Test.Case.PST")


Ideal.Outcome<-c("Easy.Example.Test","Medium.Example.Test","Hard.Example.Test","Truly.Hard.Test.Case.PST")

jamesrobin 回答:如何在首字母缩写大写的同时仅将每个单词的首字母大写?

我花了一段时间找出最佳的通用规则,以使用正则表达式规则和字符串替换来解决此问题。该解决方案不是很好,但是它在大多数情况下都可以使用,更准确的答案将不会像我所需要的那样普遍。下面是我工作答案的另一个示例。

我试图将正则表达式拆分为三个单独的str_replace_all()命令,但是结果并不令人满意,因此我们需要这个庞大的正则表达式来进行所需的分组和匹配。

Example<-c("Easy Example Test","Medium..example TEst","Hard exampleTEST","Truly HARd TestCase  PST","AnotherTESTof5FT2In","AnotherTESTof5FTT2In","ExampleOfCommonProblem")


  Example<-stringr::str_replace_all(Example,"[[:punct:]]"," ")

  Example<-stringr::str_replace_all(Example,"(([[:lower:]]|[[:digit:]]){1}(?=[[:upper:]])|[[:upper:]]{2,}(?=([[:lower:]]|[[:digit:]]))|([[:lower:]]){1,}(?=[[:digit:]]))","\\1 ")

  Example<-stringr::str_replace_all(Example,"\\s{1,}",".")

  Example

下面是上面代码的控制台输出,它不能提供完美的答案,但可以解决大多数测试用例。


>   Example
[1] "Easy.Example.Test"          "Medium.example.TE.st"      
[3] "Hard.example.TEST"          "Truly.HAR.d.Test.Case.PST" 
[5] "Another.TEST.of.5.FT.2.In"  "Another.TEST.of.5.FTT.2.In"
[7] "Example.Of.Common.Problem" 

本文链接:https://www.f2er.com/3142286.html

大家都在问