martinkabe
martinkabe

Reputation: 1139

Exact string matching in r

I struggling with exact string matching in R. I need only exact match in sentece with searched string:

sentence2 <- "laptop is a great product"
words2 <- c("top","laptop")

I was trying something like this:

sub(paste(c("^",words2,"$")),"",sentence2)

and I need replace laptop by empty string only - for exact match (laptop) but didn't work...

Please, could you help me. Thanks in advance.

Desired output:

is a great product

Upvotes: 3

Views: 1228

Answers (2)

jbaums
jbaums

Reputation: 27408

If you want to match entire words, then you can use \\b to match word boundaries.

gsub(paste0('\\b', words2, '\\b', collapse='|'), '', sentence2)

## [1] " is a great product"

Add optional whitespace to the pattern if you want to replace the adjacent spaces as well.

gsub(paste0('\\s*\\b', words2, '\\b\\s*', collapse='|'), '', sentence2)

## [1] "is a great product"

Upvotes: 2

Cath
Cath

Reputation: 24074

You can try:

gsub(paste0("^",words2," ",collapse="|"),"",sentence2)
#[1] "is a great product"

The result of paste0("^",words2," ",collapse="|") is "^top |^laptop " which means "either 'top' at the beginning of string followed by a space or 'laptop' at the beginning of string followed by a space".

Upvotes: 3

Related Questions