问题
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
回答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.
回答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'".
来源:https://stackoverflow.com/questions/18791354/find-a-string-in-another-string-in-r