检查字符串在R中是否为大写 [英] Checking if string is in uppercase in R
问题描述
是否有更简单的方法来完全匹配正则表达式模式?例如,要检查给定的字符串是否为大写,以下 2 种方法似乎太复杂了.检查 stringr 我也没有发现更简单的解决方案的迹象.
Is there simpler method to match regex pattern in its entirety? For example, to check if given string is uppercase the following 2 methods but seem too complex. Checking stringr I found no indication for simpler solution either.
方法一:
isUpperMethod1 <- function(s) {
return (all(grepl("[[:upper:]]", strsplit(s, "")[[1]])))
}
方法二:
isUpperMethod2 <- function(s) {
m = regexpr("[[:upper:]]+", s)
return (regmatches(s, m) == s)
}
我有意省略了对空、NA、NULL 字符串的处理以避免代码臃肿.
I intentionally omit handling of empty, NA, NULL strings to avoid bloated code.
大写模式可以推广到任意正则表达式模式(或字符集).
我认为上述两种解决方案都没有问题,只是它们对于解决的问题来说似乎过于复杂.
I see no problems with both solutions above except that they seem excessively complex for the problem solved.
推荐答案
您可以使用 ^
和 $
模式来匹配字符串的开头和结尾>
You can use the ^
and $
patterns to match the beginning and end of the string
grepl("^[[:upper:]]+$", s)
这篇关于检查字符串在R中是否为大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!