How to get words that end with specific characters inside each string r

I have a vector of strings that looks like this:

str <- c("bills slashed for poor families today", "your calls are charged", "complaints dept awaiting refund")

      

I want to get all words that end with a letter s

and delete s

. I tried:

gsub("s$","",str)

      

but it doesn't work because it tries to match lines ending with s

instead of words. I am trying to get output that looks like this:

[1] bill slashed for poor familie today
[2] your call are charged
[3] complaint dept awaiting refund

      

Any guidance on how I can do this? Thanks to

+3


source to share


3 answers


$

checks for end of line, not end of word.

To check word boundaries you should use \b



So:

gsub("s\\b", "", str)

      

+5


source


You can also use a positive statement:

gsub(pattern = "s{1}(?>\\s)", " ", x = str, perl = T)

      



I'm not a regex expert, but I believe this expression looks for an "s" if it is followed by a space. If it finds a match, it replaces it with a space. So the final "s" are removed.

0


source


Here's a non-basic R solution:

library(rebus)
library(stringr)

plurals <- "s" %R% BOUNDARY
str_replace_all(str, pattern = plurals, replacement = "")

      

0


source







All Articles