Find a string in another string in R

40,702

Solution 1

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.

Solution 2

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'".

Share:
40,702
user2498657
Author by

user2498657

Updated on July 15, 2022

Comments

  • user2498657
    user2498657 almost 2 years

    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