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

时间:2018-01-30 08:40:25

标签: r regex string uppercase

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

我有这样的问题

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

我期待输出为

FALSE,TRUE,FALSE

3 个答案:

答案 0 :(得分:4)

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

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

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

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

答案 1 :(得分:2)

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

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

#[1] FALSE  TRUE FALSE

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

的参数中执行此操作

答案 2 :(得分:1)

如果需要,可以使用更多详细信息解决此问题。

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"