Alexander
Alexander

Reputation: 4635

replacing second occurence of string with different string

I have very simple issue with replacing the strings second occurrence with the new string.

Lets say we have this string

string <- c("A12A32") 

and we want to replace the second A with B string. A12B32 is the expected output.

by following this relevant post How to replace second or more occurrences of a dot from a column name

I tried,

replace_second_A <-  sub("(\\A)\\A","\\1B",  string)
print(replace_second_A)

[1] "A12A32"

it seems no change in the second A why?

Upvotes: 0

Views: 78

Answers (2)

neilfws
neilfws

Reputation: 33782

First, there is no need to escape the letter A using backslashes. They are only required to escape special characters that have other meanings e.g. "." means "any character", "\\." means "period".

Second, your regular expression "(\\A)\\A" reads "match A followed by another A, keeping the first A for reuse." You don't have two consecutive "A", they are separated by digits.

So this works ("\\d+" means "match 1 or more digits"):

sub("(A\\d+)A","\\1B",  "A12A32")
[1] "A12B32"

Upvotes: 2

G. Grothendieck
G. Grothendieck

Reputation: 269714

Note that .*? matches the shortest string until the next A:

string <- "A12A32"
sub("(A.*?)A", "\\1B", string)
## [1] "A12B32"

Upvotes: 3

Related Questions