StanLe StanLe - 1 year ago 52
R Question

R - test if first occurrence of string1 is followed by string2

I have an R string, with the format

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

I simply want a way of checking if
in the first position. In other words, after the first
symbol, is the single number a "2"? How do I do this in R?

I'm assuming I need some complicated regex expresion?


39820432_2_349802j_32hfh = TRUE

43lda821_9_428fj_2f = FALSE
(notice there is a
there, but not in the right spot)

Answer Source
> grepl("^[^_]+_1",s)
> grepl("^[^_]+_2",s)
[1] TRUE

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

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