如何使用grep()来查找完全匹配 [英] How to use grep() to find exact match

查看:1337
本文介绍了如何使用grep()来查找完全匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  string = c(apple,apples,applez)
grep(apple,string)

这将为我提供 string 中所有三个元素的索引。但我想要一个完全匹配的单词苹果(即我只想 grep()返回索引1)。

解决方案

使用单词边界 \ b 和非单词字符,

  string = c(apple,apples,applez)
grep(\\\\ bapple \\b,string)
[1] 1

OR

使用锚点。 ^ 声明我们正处于开始阶段。 $ 断言我们在最后。

  grep(^ apple $,string)
[1] 1

您可以将正则表达式存储在

  pat < - \\bapple\\
grep(pat,string)
[1] 1
pat < - ^ apple $
grep(pat,string)
[1] 1

更新:

  paste(^,pat,$,sep =)
[1]^ apple $
string
[1]appleapple:s (^,pat,$,sep =),字符串)
[ 1] 1


string = c("apple", "apples", "applez")
grep("apple", string)

This would give me the index for all three elements in string. But I want an exact match on the word "apple" (i.e I just want grep() to return index 1).

解决方案

Use word boundary \b which matches a between a word and non-word character,

string = c("apple", "apples", "applez")
grep("\\bapple\\b", string)
[1] 1

OR

Use anchors. ^ Asserts that we are at the start. $ Asserts that we are at the end.

grep("^apple$", string)
[1] 1

You could store the regex inside a variable and then use it like below.

pat <- "\\bapple\\b"
grep(pat, string)
[1] 1
pat <- "^apple$"
grep(pat, string)
[1] 1

Update:

paste("^",pat,"$", sep="")
[1] "^apple$"
string
[1] "apple"   "apple:s" "applez" 
pat
[1] "apple"
grep(paste("^",pat,"$", sep=""), string)
[1] 1

这篇关于如何使用grep()来查找完全匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆