Insert counter after regular expression in string

Insert counter after match in row

I am trying to insert the suffix count after each match in a string.

For example: Insert a number after each matching "o" in the following line:

"The Apollo program was conceived early in 1960"

It will look like this:

"The Apo1llo2 pro3gram was co4nceived early in 1960"

I think I should use gsub, perhaps, with perl = TRUE, but I do not know how.

string <- "The Apollo program was conceived early in 1960"

gsub( x = string, pattern = "(o)", replacement = "\\1 $count", perl = TRUE )
+4
source share
4 answers

An option is used here that uses a powerful combination gregexpr, regmatchesand regmatches<-:

x <- c("The Apollo program was conceived early in 1960",
       "The International Space Station was launched in 1998")

m <- gregexpr("(?<=o)", x, perl=TRUE)
regmatches(x,m) <- lapply(regmatches(x,m), seq_along)

x
# [1] "The Apo1llo2 pro3gram was co4nceived early in 1960"    
# [2] "The Internatio1nal Space Statio2n was launched in 1998"
+3
source

Here is one approach:

x <- "The Apollo program was conceived early in 1960"

library(stringi)  ## or
pacman::p_load(stringi)  ## to load and install if not found

do.call(sprintf, c(list(gsub("o", "o%s", x)), seq_len(stri_count_regex(x, "o"))))

## [1] "The Apo1llo2 pro3gram was co4nceived early in 1960"

Or more succinctly:

pacman::p_load(qdapRegex, stringi)
S(gsub("o", "o%s", x), 1:stri_count_regex(x, "o"))

. pacman qdapRegex.

+4

Another possibility using gsubfnon x@Josh O'Brien.

library(gsubfn)
p <- proto(fun = function(this, x) paste0(x, count))
gsubfn("o", p, x)

# [1] "The Apo1llo2 pro3gram was co4nceived early in 1960"    
# [2] "The Internatio1nal Space Statio2n was launched in 1998"

For further reference, please see the vignette . gsubfn

+3
source

As you noted this question as Perl, here is the Perl solution.

$string = "The Apollo program was conceived early in 1960";
$string =~ s/o/o . ++$i/eg;
say $string;
+1
source

All Articles