Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression find strings with certain pattern in R

Tags:

regex

r

I have some strings here and they are:

12ABC3, 2ABC45, ABC 56, uhyABC, REGEXP ...

The objective is as long as there is 'ABC' in a string (not 'BCA' or 'BAC') it should return TRUE when using 'grepl'

So the output should be

TRUE, TRUE, TRUE, TRUE, FALSE

Can anybody help me with this?

Thanks in advance

like image 622
Lambo Avatar asked Jan 11 '23 00:01

Lambo


2 Answers

You want to use fixed = TRUE in your call to grepl.

> x <- c("12ABC3", "2ABC45", "ABC 56", "uhyABC", "REGEXP", "BCA", "CAB")
> grepl("ABC", x, fixed = TRUE)
# [1]  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE

The fixed argument definition is

logical. If TRUE, pattern is a string to be matched as is. Overrides all conflicting arguments.

like image 128
Rich Scriven Avatar answered Jan 23 '23 05:01

Rich Scriven


You can use the following.

> x <- c('12ABC3', '2ABC45', 'ABC 56', 'uhyABC', 'REGEXP')
> grepl('ABC', x, fixed=T)
# [1]  TRUE  TRUE  TRUE  TRUE FALSE
> x[grepl('ABC', x, fixed=T)]
# [1] "12ABC3" "2ABC45" "ABC 56" "uhyABC"
like image 43
hwnd Avatar answered Jan 23 '23 05:01

hwnd