我有一个R字符串,格式是
s = `"[some letters and numbers]_[a number]_[more numbers, letters, punctuation, etc, anything]"`
我只是想要一种检查s
是否在第一个位置包含"_2"
的方法。换句话说,在第一个_
符号之后,单个数字是"2“吗?我如何在R中做到这一点?
我假设我需要一些复杂的正则表达式?
示例:
39820432_2_349802j_32hfh = TRUE
43lda821_9_428fj_2f = FALSE
(注意那里有一个_2
,但不在正确的位置)
发布于 2013-11-19 10:36:28
> grepl("^[^_]+_1",s)
[1] FALSE
> grepl("^[^_]+_2",s)
[1] TRUE
基本上,首先查找除_
之外的所有内容,然后查找_2
。
+1到@Ananda_Mahto,建议使用grepl
而不是grep
。
发布于 2014-05-26 22:37:00
我认为在这里回答通用问题“如果字符串包含字符串,则R- test”是值得的。
为此,请使用grep函数。
# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"
https://stackoverflow.com/questions/20061997
复制相似问题