h1990
h1990

Reputation: 13

How to replace the last occurrence in a character?

I have an R character vector:

a<-'aabbccaabbccaabbcc'

I want to replace the last occurrence of 'aa' and anything that follows with 'bb'. I tried using stri_replace_last of stringi package with regex (.*)aa(.*). But it replaces everything as it is a single string.

Is there any way to do this in R?

Upvotes: 1

Views: 2402

Answers (2)

akrun
akrun

Reputation: 887028

We can use gsubfn to match the two 'a' followed by zero or more characters that are not an 'a' ([^a]*) until the end ($) of the string, replace the matched string by replicating 'b' by the number of characters of the matched string.

library(gsubfn)
gsubfn("aa[^a]*$", ~strrep("b", nchar(x)), a) 
#[1] "aabbccaabbccbbbbbb"

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

a <- 'aabbccaabbccaabbcc'
first <- gsub('^(.*)aa.*$', '\\1', a)
result <- paste0(first, paste(replicate(nchar(a) - nchar(first), "b"), collapse = ""))

> a
[1] "aabbccaabbccaabbcc"
> result
[1] "aabbccaabbccbbbbbb"
                 ^^ anything which follows the last 'aa' has been replaced with 'b'

Upvotes: 4

Related Questions