检查R中的字符串是否为大写

top*_*hef 19 regex r uppercase

是否有更简单的方法来匹配正则表达式模式?例如,要检查给定的字符串是否为以下两种方法的大写,但看起来过于复杂.检查stringr我发现没有更简单的解决方案的迹象.

方法1:

isUpperMethod1 <- function(s) {
  return (all(grepl("[[:upper:]]", strsplit(s, "")[[1]])))
}
Run Code Online (Sandbox Code Playgroud)

方法2:

isUpperMethod2 <- function(s) {
  m = regexpr("[[:upper:]]+", s)
  return (regmatches(s, m) == s)
}
Run Code Online (Sandbox Code Playgroud)

我故意省略处理空,NA,NULL字符串以避免膨胀代码.

大写模式可以推广到任意正则表达式(或字符集).

我发现上述两种解决方案都没有问题,只是它们对于解决的问题看起来过于复杂.

Mat*_*rde 26

您可以使用^$模式匹配字符串的开头和结尾

grepl("^[[:upper:]]+$", s)
Run Code Online (Sandbox Code Playgroud)


小智 10

当使用"toupper"函数转换为大写时,为什么不测试单词是否与自身相同?

word1 <- "TEST"
word1 == toupper(word1) 
Run Code Online (Sandbox Code Playgroud)

将会 TRUE


fli*_*ies 8

如果你更喜欢生活在一个tidyr宇宙中,这里是使用的版本stringr

library(stringr)
str_detect(s, "^[:upper:]+$")
Run Code Online (Sandbox Code Playgroud)