user1637359
user1637359

Reputation: 227

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?

Upvotes: 1

Views: 360

Answers (2)

Shenglin Chen
Shenglin Chen

Reputation: 4554

If you just want to know whether string is a sentence, not single word, you could use: function(x) grepl('\\s',x)

Upvotes: 0

MrFlick
MrFlick

Reputation: 206308

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

Upvotes: 4

Related Questions