megmac
megmac

Reputation: 509

Removal of specific string and anything after

I would like to remove 'sat' and anything after but not 'saturday'. Although this seems quite simple I have been unable to find a thread on this.

Example:

text <- c("good morning amer sat","this morning saturday")

Desired Result:

"good morning amer","this morning saturday"

Everything I do removes saturday.

Upvotes: 2

Views: 49

Answers (3)

PaulS
PaulS

Reputation: 25323

Another possible solution, using negative lookaround and stringr::str_remove (although, I am not sure whether you want to remove sat only or remove sat and every following character):

library(stringr)

str_remove(text, "\\s*sat(?!urday).*$")

#> [1] "good morning amer"     "this morning saturday"

Upvotes: 1

TarJae
TarJae

Reputation: 78917

Here with str_replace:

library(stringr)

str_replace(text, ' sat$', '')

[1] "good morning amer"    
[2] "this morning saturday"

Upvotes: 3

akrun
akrun

Reputation: 887028

We could use word boundary (\\b)

sub("\\s*\\bsat\\b", "", text)

-output

[1] "good morning amer"     "this morning saturday"

Or with stringr

library(stringr)
str_remove(text, "\\s*\\bsat\\b")
[1] "good morning amer"     "this morning saturday"

Upvotes: 3

Related Questions