从[A-Z]中提取包含字符串的值

时间:2018-01-08 10:38:21

标签: r regex

我试图从矢量中动态提取那些带有[A-Z]字符串的值(它们也可能包含数字),而不是在“str”中指定它们

我的代码如下:

strings <- c("1", "70.5", "sh", "av", "3", "12","as","da","da","azz1")
     str <- c("sh", "av","as","da","azz1")
    matches <- unique (grep(paste(str,collapse="|"), 
                            strings, value=TRUE))

1 个答案:

答案 0 :(得分:1)

你可以尝试:

> unique(grep("^[a-zA-Z]", strings, value = TRUE))
[1] "sh"   "av"   "as"   "da"   "azz1"

这应该允许您以小写和大写字符开头的字符串。另一个大写字符的例子:

> strings2 <- c("1", "70.5", "sh", "aV", "3", "12","as","da","da","azz1","DA")
> unique(grep("^[a-zA-Z]", strings2, value = TRUE))
[1] "sh"   "aV"   "as"   "da"   "azz1" "DA"