R - test if the first input of line1 is followed by line2

I have a string R, with the format

s = `"[some letters and numbers]_[a number]_[more numbers, letters, punctuation, etc, anything]"` 

I just want to check if s contains "_2" in the first position. In other words, after the first character _ , is this the singular a "2"? How to do it in R?

I guess I need some kind of complex regex expression?

Examples:

 39820432_2_349802j_32hfh = TRUE 

43lda821_9_428fj_2f = FALSE (note that there is _2 , but not in the right place)

+51
contains r
Nov 19 '13 at 2:29
source share
2 answers
 > grepl("^[^_]+_1",s) [1] FALSE > grepl("^[^_]+_2",s) [1] TRUE 

in principle, look for everything at the beginning, except for _ , and then _2 .

+1 to @Ananda_Mahto for the grepl instead of grep .

+66
Nov 19 '13 at 2:36 on
source share
โ€” -

I think itโ€™s worth answering the general question "R - test if the string contains the string" here.

Use grep for this.

 # 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" 
+30
May 26 '14 at 14:37
source share



All Articles