简体   繁体   English

如何在grepl函数中的Perl中进行正则表达式匹配?

[英]How to perl regex match in R in the grepl function?

I have a function in R which uses the grepl command as follows: 我在R中有一个使用grepl命令的函数,如下所示:

function(x) grepl('\bx\b',res$label, perl=T)

This doesn't seem to work - the 'x' input is a character type string (a sentence), and i'd like to create word boundaries around the 'x' as I match, as I don't want the term to pull out other terms in the table I am searching through which contains some similar terms. 这似乎不起作用-“ x”输入是一个字符串(一个句子),我想在匹配时在“ x”周围创建单词边界,因为我不希望该术语在我正在搜索的表中拉出其他术语,其中包含一些相似的术语。

Any suggestions? 有什么建议么?

You just need to properly escape the slash in your regex 您只需要在正则表达式中正确避开斜杠

ff<-function(x) grepl('\\bx\\b',x, perl=T)
ff(c("axa","a x a", "xa", "ax","x"))
# [1] FALSE  TRUE FALSE FALSE  TRUE

如果您只是想知道字符串是否是句子而不是单个单词,则可以使用: function(x) grepl('\\\\s',x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM