将字符串中每个单词的第一个字母大写,除了`in`,````of`

时间:2016-01-14 09:03:54

标签: regex r gsub

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

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) 

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

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

您可以使用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,其中提供了一些关于要包含在第一个替代组中的单词的提示。

RegEx说明:

  • (?<!^) - 如果不是在字符串的开头,则仅匹配以下备选方案(我在评论中添加了此限制,有一项要求 第一个字母应始终大写。
  • \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,该字母与单词中的起始字母相匹配。

答案 2 :(得分:1)

我对正则表达式并不擅长,所以找到了另一种选择。 d是需要排除的单词矢量。

我们使用strsplit将字符串拆分为单词,然后检查是否有任何单词与向量d匹配,如果它没有,则我们使用{{1}将其大写capitalize包中的函数。

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" sapply将其作为字符串向量

paste