我试图确定一个字符串是否是另一个字符串的子集。例如:
chars <- "test"
value <- "es"
如果“value”作为字符串“chars”的一部分出现,我想返回TRUE。在下面的场景中,我想返回false:
chars <- "test"
value <- "et"
我试图确定一个字符串是否是另一个字符串的子集。例如:
chars <- "test"
value <- "es"
如果“value”作为字符串“chars”的一部分出现,我想返回TRUE。在下面的场景中,我想返回false:
chars <- "test"
value <- "et"
当前回答
你想要grepl:
> chars <- "test"
> value <- "es"
> grepl(value, chars)
[1] TRUE
> chars <- "test"
> value <- "et"
> grepl(value, chars)
[1] FALSE
其他回答
如果你也想检查一个字符串(或一组字符串)是否包含多个子字符串,你也可以在两个子字符串之间使用'|'。
>substring="as|at"
>string_vector=c("ass","ear","eye","heat")
>grepl(substring,string_vector)
你会得到
[1] TRUE FALSE FALSE TRUE
因为第一个单词包含子字符串“as”,而最后一个单词包含子字符串“at”
你想要grepl:
> chars <- "test"
> value <- "es"
> grepl(value, chars)
[1] TRUE
> chars <- "test"
> value <- "et"
> grepl(value, chars)
[1] FALSE
使用grepl函数
grepl( needle, haystack, fixed = TRUE)
像这样:
grepl(value, chars, fixed = TRUE)
# TRUE
使用?grepl获取更多信息。
使用grep或grepl,但要注意是否要使用正则表达式。
默认情况下,grep和相关的匹配采用正则表达式,而不是文字子字符串。如果你没有预料到,并且你试图匹配一个无效的正则表达式,它就不起作用:
> grep("[", "abc[")
Error in grep("[", "abc[") :
invalid regular expression '[', reason 'Missing ']''
要做一个真子字符串测试,使用fixed = true。
> grep("[", "abc[", fixed = TRUE)
[1] 1
如果你确实想要正则表达式,很好,但这并不是OP所要求的。
同样,可以使用"stringr"库:
> library(stringr)
> chars <- "test"
> value <- "es"
> str_detect(chars, value)
[1] TRUE
### For multiple value case:
> value <- c("es", "l", "est", "a", "test")
> str_detect(chars, value)
[1] TRUE FALSE TRUE FALSE TRUE