且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用stringr检测字符串中的整个单词

更新时间:2023-02-18 16:37:27

我们可以添加词边界为 \\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")