如何使用stringr检测字符串中的整个单词 [英] how to a detect whole word in a string using stringr

查看:32
本文介绍了如何使用stringr检测字符串中的整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 str_detect 检测整个单词.应该很简单,但我做对了...
这应该返回 FALSE,但它返回 TRUE.

I'm trying to detect a whole word using str_detect. It should be simple, but I can't get it right...
This should return FALSE, but it returns TRUE.

str_detect("堡盟 PBMN PTransmitter 0-600bar#324664",pattern="600")

并添加 boundary 抛出错误

str_detect(string="堡盟 PBMN PTransmitter 0-600bar#324664",pattern="600",boundary("word"))

感谢您的帮助.

推荐答案

我们可以添加词边界为 \\b.如果 pattern 是可变的,我们可以使用 paste0 将它与单词边界连接起来.

We can add word boundaries as \\b. If the pattern is variable we can use paste0 to concatenate it with word boundaries.

pn <- "600"
stringr::str_detect("Baumer PBMN PTransmitter 0-600bar#324664", paste0('\\b', pn, '\\b'))
#[1] FALSE

同样也可以使用 grepl

grepl(paste0('\\b', pn, '\\b'), "Baumer PBMN PTransmitter 0-600bar#324664")

这篇关于如何使用stringr检测字符串中的整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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