user2498657
user2498657

Reputation: 377

Find a string in another string in R

I want to find a string within another string in R. The strings are as follows. I want to be able to match string a to string b as and the out put should be a == b which returns TRUE

a <- "6250;7250;6251"
b <- "7250"
a == b                 #FALSE

Upvotes: 3

Views: 45501

Answers (2)

Greg Snow
Greg Snow

Reputation: 49660

If b were to equal 725 instead of 7250, would you still want the result to be TRUE?

If so then the grepl answer already given will work (and you could speed it up a bit by setting fixed=TRUE since there are no patterns to be matched.

If you only want TRUE when there is an exact match to something between ; then you will either need to embed b into a regular expression (sprintf may be of help), or simpler, use strsplit to split a into just the parts to be matched, then use %in% to see if b is a match to any of those values.

Upvotes: 4

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

You can use regmatches and gregexpr, but your question is somewhat vague at the moment, so I'm not positive that this is what you're looking for:

> regmatches(a, gregexpr(b, a))
[[1]]
[1] "7250"

> regmatches(a, gregexpr(b, a), invert=TRUE)
[[1]]
[1] "6250;" ";6251"

Based on your updated question, you're probably looking for grepl.

> grepl(b, a)
[1] TRUE
> grepl(999, a)
[1] FALSE

^^ We're essentially saying "look for 'b' in 'a'".

Upvotes: 12

Related Questions