
[英]Capitalize the first letter of each word in a string except `in`, `the` `of`
[英]How to capitalize only the first letter of each word while keeping acronyms capitalized?
我正在编写 function 来自动清理变量名以生成同质变量名。 通常将“This is anExample”之类的内容转换为“This.Is.An.Example”。 通常所有这些都很容易,但是我在变量名中包含的首字母缩写词遇到了麻烦。
一个例子是:“Clock in Time PST”理想情况下会变成“Clock.In.Time.PST”
我考虑将 str_to_upper 修改为 function,但我不知道 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")
我花了一段时间找出最好的通用规则,以便使用正则表达式规则和字符串替换来解决这个问题。 该解决方案不是很漂亮,但它在大多数情况下都有效,并且更准确的答案不会像我需要的那样通用。 下面是我的工作答案的另一个示例。
我尝试将正则表达式拆分应用于三个单独的 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
下面是上面代码中的控制台 output,它不能提供完美的答案,但可以解决绝大多数测试用例。
> 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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.