在 R 中使用 grepl 完成单词匹配 [英] Complete word matching using grepl in R

查看:52
本文介绍了在 R 中使用 grepl 完成单词匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例:

> testLines <- c("I don't want to match this","This is what I want to match")
> grepl('is',testLines)
> [1] TRUE TRUE

不过,我想要的是仅在is"作为一个词单独存在时才匹配它.通过阅读一些 perl 文档,似乎这样做的方法是使用 \b,这是一个锚点,可用于识别模式前后的内容,即 \bword\b 匹配 'word' 但不匹配 'sword'.所以我尝试了以下示例,使用 Perl 语法设置为TRUE":

What I want, though, is to only match 'is' when it stands alone as a single word. From reading a bit of perl documentation, it seemed that the way to do this is with \b, an anchor that can be used to identify what comes before and after the patter, i.e. \bword\b matches 'word' but not 'sword'. So I tried the following example, with use of Perl syntax set to 'TRUE':

> grepl('\bis\b',testLines,perl=TRUE)
> [1] FALSE FALSE

我正在寻找的输出是 FALSE TRUE.

The output I'm looking for is FALSE TRUE.

推荐答案

"\<"是单词开头的另一个转义序列,\>"是结尾.在 R 字符串中,您需要将反斜杠加倍,因此:

"\<" is another escape sequence for the beginning of a word, and "\>" is the end. In R strings you need to double the backslashes, so:

> grepl("\\<is\\>", c("this", "who is it?", "is it?", "it is!", "iso"))
[1] FALSE  TRUE  TRUE  TRUE FALSE

请注意,这匹配是!"但不是iso".

Note that this matches "is!" but not "iso".

这篇关于在 R 中使用 grepl 完成单词匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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