将字符串中除 `in`、`the` `of` 之外的每个单词的首字母大写

Capitalize the first letter of each word in a string except `in`, `the` `of`

除了某些单词外,如何将每个单词的首字母大写

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) 

每个单词的第一个字母大写。

以下正则表达式可实现您的目标:

\b(?!(?:in|the|of)\b)([a-z])
# look for a word boundary on the left
# assure that in/the/of is not following immediately 
# (including word boundary, thanks to @stribizhev)
# match and capture a lowercase letter

这些匹配的字母(在第 1 组中)需要更改为大写字母。参见 a working demo on regex101

在 R 中:

sapply(x, gsub, pattern = "\b(?!(?:in|the|of)\b)([a-z])", replacement = "\U\1", 
  perl = TRUE, USE.NAMES = FALSE)
## [1] "I Like the Pizza"      "The Water in the Pool"

您可以使用 PCRE RegEx 应用黑名单方法:

(?<!^)\b(?:the|an?|[io]n|at|with|from)\b(*SKIP)(*FAIL)|\b(\pL)

这是一个demo of what this regex matches

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

IDEONE demo

这是一篇文章 Words Which Should Not Be Capitalized in a Title,其中包含一些关于将哪些词包含在第一个备选组中的提示。

正则表达式解释:

  • (?<!^) - 如果不在字符串的开头,则只匹配以下替代项(我在注释中添加了此限制,要求 第一个字母应始终大写。)
  • \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) - 捕获组 1 匹配作为单词中的起始字母的字母。

我不擅长正则表达式,所以找到了替代方法。 d 是需要排除的单词向量。

我们使用 strsplit 将字符串拆分为单词,然后检查是否有任何单词与向量 d 匹配,如果不匹配,则我们使用 [=15= 将其大写] Hmisc 包中的函数。

library(Hmisc)
x <- c('I like the pizza', 'The water in the pool')
d <- c("the","of","in")
lapply(strsplit(x, " "), function(x) ifelse(is.na(match(x, d)), capitalize(x),x))

# [[1]]
#[1] "I"     "Like"  "the"   "Pizza"

#[[2]]
#[1] "The"   "Water" "in"    "the"   "Pool" 

此外,您可以使用 sapplypaste 将其作为字符串向量取回

a <- lapply(strsplit(x, " "), function(x) ifelse(is.na(match(x, d)), capitalize(x),x))
sapply(a, function(x) paste(x, collapse = ' '))

#[1] "I Like the Pizza"      "The Water in the Pool"