简体   繁体   中英

How to perl regex match in R in the grepl function?

I have a function in R which uses the grepl command as follows:

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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