elbord77
elbord77

Reputation: 353

Insert a number after every occurence of a string from a set of strings in a string

Let's say I have a set of strings strset <- c("Apple", "Ball", "Cat1s")

I'm looking for a way to insert a given number (eg. 21) after every occurrence of a string from strset in a new string such as "[Apple][Ball][Cat1s|Apple][Cat1s|Blah:Ball]" to convert it to "[Apple21][Ball21][Cat1s21|Apple21][Cat1s21|Blah:Ball21]".

Edit:

[oneApple][Ball|Balls] should become [oneApple][Ball21|Balls] not [oneApple21][Ball21|Ball21s].

Upvotes: 1

Views: 88

Answers (4)

Code Maniac
Code Maniac

Reputation: 37755

To avoid replacing strings such [oneApple] you need to consider word boundaries also while building your regex pattern

strset<-c("Apple", "Ball", "Cat1s")
str2<-"[Apple][Ball][Cat1s|Apple][Cat1s|Blah:Ball][oneApple][Ball|Balls]"
gsub(paste0("(\\b(?:", paste0(strset, collapse="|"),")\\b)"), "\\121", str2)

//output [1] "[Apple21][Ball21][Cat1s21|Apple21][Cat1s21|Blah:Ball21][oneApple][Ball21|Balls]"

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389175

We can also use stringr::str_replace_all

library(stringr)
str_replace_all(strset1, paste0(strset, collapse = "|"), function(m) str_c(m, 21))
#[1] "[Apple21][Ball21][Cat1s21|Apple21][Cat1s21|Blah:Ball21]"

data

strset <- c("Apple", "Ball", "Cat1s")
strset1 <- "[Apple][Ball][Cat1s|Apple][Cat1s|Blah:Ball]"

Upvotes: 1

Hayden Y.
Hayden Y.

Reputation: 448

Using paste with collapse="|" and then gsub with backreferencing should get the job done.

strset<-c("Apple", "Ball", "Cat1s")
str2<-"[Apple][Ball][Cat1s|Apple][Cat1s|Blah:Ball]"
gsub(paste0("(", paste0(strset, collapse="|"),")"), "\\121", str2)

Upvotes: 5

Shree
Shree

Reputation: 11150

Here's a way using gsub -

strset <- c("Apple", "Ball", "Cat1s")

test <- "[Apple][Ball][Cat1s|Apple][Cat1s|Blah:Ball]"

for(i in strset) {
  test <- gsub(i, paste0(i, "21"), test)
}

test
[1] "[Apple21][Ball21][Cat1s21|Apple21][Cat1s21|Blah:Ball21]"

Upvotes: 1

Related Questions