在R中使用grep来查找字符串作为整个单词(但不是作为单词的一部分的字符串) [英] Using grep in R to find strings as whole words (but not strings as part of words)

查看:91
本文介绍了在R中使用grep来查找字符串作为整个单词(但不是作为单词的一部分的字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找正确的正则表达式。以下

  t1 = c(IGF2,IGF2AS,INS,TH,TH,THZH,ZGTH )
grep(TH,t1,value = T)

返回所有元素 t1 ,但只有第一个和第二个是正确的。我只是想用词/短语 TH 返回的条目?

解决方案

您需要添加字边界定位符 \b ),因此只有整个单词将被匹配(即单词包围非单词字符或字符串的开始/结尾,其中单词字符表示 \w

尝试

  c $ c>,即字母数字字符) grep(\\\\ bTH\\b,t3,value = T)


I'm searching for the right regular expression. The following

t1 = c("IGF2, IGF2AS, INS, TH", "TH", "THZH", "ZGTH")
grep("TH",t1, value=T)

returns all elements of t1, but only the first and second are correct. I just want entries with word/phrase TH returned?

解决方案

You need to add word boundary anchors (\b) around your search strings so only entire words will be matched (i. e. words surrounded by non-word characters or start/end of string, where "word character" means \w, i.e. alphanumeric character).

Try

grep("\\bTH\\b",t3, value=T)

这篇关于在R中使用grep来查找字符串作为整个单词(但不是作为单词的一部分的字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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