Evan O.
Evan O.

Reputation: 1563

Replacing string component only if/when condition is met?

Right now, I'm trying to set up a condition so that, if there is a word that ends with an "s", and there are 4 or more characters prior to that "s", then add an apostraphe (') prior to the "s" for that word.

So transform "his computers applesauce" to "his computer's applesauce"

Any idea how I'd do this?

The issue I'm having is that this doesn't work (for good reason):

library(stringr)

str_replace_all("his computers applesauce", "\\b[a-z]{4,}s\\b", "\\b[a-z]{4,}'s\\b")
#> [1] "his b[a-z]{4,}'sb applesauce"

Upvotes: 1

Views: 48

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

You're trying to replace the match with the regex itself.

you need to capture group. \b([a-zA-Z]{4,})(s)\b like this

library(stringr)

str_replace_all("his computers applesauce", "\\b([a-z]{4,})(s)\\b", "\\1'\\2")

Upvotes: 1

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You need to capture the word in a group (say group 1) and then while replacing you can back reference it using \\1 and accordingly do the substitution.

Just change your string from,

str_replace_all("his computers applesauce", "\\b[a-z]{4,}s\\b", "\\b[a-z]{4,}'s\\b")

to

str_replace_all("his computers applesauce", "\\b([a-z]{4,})s\\b", "\\1's")

Upvotes: 3

Related Questions