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

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

问题描述

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

这将为我提供 string 中所有三个元素的索引.但我想要apple"这个词的精确匹配(即我只想要 grep() 返回索引 1).

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).

推荐答案

使用词边界 \b 匹配一个单词和非单词字符之间的 a,

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

使用锚点.^ 断言我们在开始.$ 断言我们到了最后.

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

更新:

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

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

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