繁体   English   中英

检测每个单词的第一个字母是否是大写字母

[英]Detect if the first letter of each word is in capital letters

我试图检测给定字符串中每个单词的首字母是否为大写字母。

我有这样的问题

x <- c("Bachelor of Technology - Computers + Bachelor of Technology - Science",
       "Hello Sam ,How Are You?", "Certificate - Internet and Web Technology")

我期待输出为

FALSE,TRUE,FALSE

如何检查相反的(字边界后跟小写字母)并否定结果?

!grepl("\\b(?=[a-z])", x, perl = TRUE)
#[1] FALSE  TRUE FALSE

如果您只想考虑空格字符后面的单词,可以将其调整为:

!grepl("\\s+[a-z]", x)

这是一种非正则表达式方法,

sapply(strsplit(x, '[[:punct:]]|\\s+'), function(i){i1 <- substr(trimws(i), 1, 1); 
                                              all(i1[i1 != ''] == toupper(i1[i1 != '']))})

#[1] FALSE  TRUE FALSE

如果要添加/删除分隔符,可以在strsplit的参数中strsplit

如果需要,可以使用更多细节的解决方案。

library(stringi)
#split string into its single elements but maintain all elements
#by using lookaround regex
x_split <- stri_split_regex(x, "(?=\\b)")
#check each element in uppercase
upper_check <- lapply(x_split, function(x) stri_detect_regex(x, "^\\p{Lu}"))
#combine the information
#(all steps might of course be done in a single call,
#just separated the steps here for demonstration)
mapply(function(x,y) rbind(string = x, start_w_upper = y), x_split, upper_check)
# [[1]]
#              [,1]    [,2]       [,3]    [,4]    [,5]    [,6]         [,7]    [,8]        [,9]    [,10]      [,11]  
# string        ""      "Bachelor" " "     "of"    " "     "Technology" " - "   "Computers" " + "   "Bachelor" " "    
# start_w_upper "FALSE" "TRUE"     "FALSE" "FALSE" "FALSE" "TRUE"       "FALSE" "TRUE"      "FALSE" "TRUE"     "FALSE"
# [,12]   [,13]   [,14]        [,15]   [,16]     [,17]  
# string        "of"    " "     "Technology" " - "   "Science" ""     
# start_w_upper "FALSE" "FALSE" "TRUE"       "FALSE" "TRUE"    "FALSE"
# 
# [[2]]
#              [,1]    [,2]    [,3]    [,4]   [,5]    [,6]   [,7]    [,8]   [,9]    [,10]  [,11]  
# string        ""      "Hello" " "     "Sam"  " ,"    "How"  " "     "Are"  " "     "You"  "?"    
# start_w_upper "FALSE" "TRUE"  "FALSE" "TRUE" "FALSE" "TRUE" "FALSE" "TRUE" "FALSE" "TRUE" "FALSE"
# 
# [[3]]
#              [,1]    [,2]          [,3]    [,4]       [,5]    [,6]    [,7]    [,8]   [,9]    [,10]        [,11]  
# string        ""      "Certificate" " - "   "Internet" " "     "and"   " "     "Web"  " "     "Technology" ""     
# start_w_upper "FALSE" "TRUE"        "FALSE" "TRUE"     "FALSE" "FALSE" "FALSE" "TRUE" "FALSE" "TRUE"       "FALSE"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM