除了某些单词之外,如何将每个单词的第一个字母大写
x <- c('I like the pizza', 'The water in the pool')
我期望输出是
c('I Like the Pizza', 'The Water in the Pool')
目前我正在使用
gsub('(^|[[:space:]])([[:alpha:]])', '\\1\\U\\2', x, perl=T)
每个单词的第一个字母大写。
您可以使用 PCRE RegEx 应用黑名单方法:
(?<!^)\b(?:the|an?|[io]n|at|with|from)\b(*SKIP)(*FAIL)|\b(\pL)
这是一个该正则表达式匹配内容的演示 https://regex101.com/r/fQ3sY9/2.
In R:
x <- c('I like the pizza', 'The water in the pool', 'the water in the pool')
gsub("(?<!^)\\b(?:the|an?|[io]n|at|with(?:out)?|from|for|and|but|n?or|yet|[st]o|around|by|after|along|from|of)\\b(*SKIP)(*FAIL)|\\b(\\pL)", "\\U\\1", x, perl=T)
## => [1] "I Like the Pizza" "The Water in the Pool" "The Water in the Pool"
See IDEONE演示 https://ideone.com/jmajK8
这是一篇文章标题中不应大写的单词 http://www.superheronation.com/2011/08/16/words-that-should-not-be-capitalized-in-titles/关于第一个替代组中应包含哪些单词的一些提示。
正则表达式解释:
-
(?<!^)
- 如果不在字符串开头,则仅匹配以下替代项(我在注释中添加了此限制,有一个要求第一个字母应始终大写。)
-
\b
- 前导词边界
-
(?:the|an?|[io]n|at|with(?:out)?|from|for|and|but|n?or|yet|[st]o|around|by|after|along|from|of)
- 白名单虚词(可以而且应该延长!)
-
\b
- 尾随字边界
-
(*SKIP)(*FAIL)
- 比赛失败一旦功能词匹配
-
|
- or...
-
\b(\pL)
- 捕获与单词中的起始字母匹配的组 1。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)