string 在 R 中的另一个字符串中查找一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18791354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find a string in another string in R
提问by user2498657
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
我想在 R 中的另一个字符串中找到一个字符串。字符串如下。我希望能够将字符串 a 与字符串 b 匹配,输出应该是a == b
返回 TRUE
a <- "6250;7250;6251"
b <- "7250"
a == b #FALSE
回答by A5C1D2H2I1M1N2O1R2T1
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
and gregexpr
,但目前您的问题有些含糊,所以我不确定这就是您要寻找的内容:
> 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
.
> grepl(b, a)
[1] TRUE
> grepl(999, a)
[1] FALSE
^^ We're essentially saying "look for 'b' in 'a'".
^^ 我们实际上是在说“在‘a’中寻找‘b’”。
回答by Greg Snow
If b were to equal 725
instead of 7250
, would you still want the result to be TRUE
?
如果 b 等于725
而不是7250
,您还希望结果是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.
如果是这样,那么grepl
已经给出的答案将起作用(并且您可以通过设置加快速度,fixed=TRUE
因为没有要匹配的模式。
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.
如果您只想要TRUE
与两者之间的某些内容完全匹配,;
那么您要么需要嵌入b
正则表达式(sprintf
可能会有所帮助),或者更简单,用于strsplit
拆分a
为仅要匹配的部分,然后用于%in%
查看是否b
与这些值中的任何一个匹配。