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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:05:28  来源:igfitidea点击:

Find a string in another string in R

stringrcompare

提问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 == bwhich returns TRUE

我想在 R 中的另一个字符串中找到一个字符串。字符串如下。我希望能够将字符串 a 与字符串 b 匹配,输出应该是a == b返回 TRUE

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

回答by A5C1D2H2I1M1N2O1R2T1

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

您可以使用regmatchesand 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 725instead of 7250, would you still want the result to be TRUE?

如果 b 等于725而不是7250,您还希望结果是TRUE吗?

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

如果是这样,那么grepl已经给出的答案将起作用(并且您可以通过设置加快速度,fixed=TRUE因为没有要匹配的模式。

If you only want TRUEwhen there is an exact match to something between ;then you will either need to embed binto a regular expression (sprintfmay be of help), or simpler, use strsplitto split ainto just the parts to be matched, then use %in%to see if bis a match to any of those values.

如果您只想要TRUE与两者之间的某些内容完全匹配,;那么您要么需要嵌入b正则表达式(sprintf可能会有所帮助),或者更简单,用于strsplit拆分a为仅要匹配的部分,然后用于%in%查看是否b与这些值中的任何一个匹配。