Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert counter after regex match in string

Tags:

regex

r

perl

Insert counter after match in string

I'm trying to insert a count-suffix after each match in a string.

For example: Inserting a number after each matched "o" in the following string:

"The Apollo program was conceived early in 1960"

Would look like:

"The Apo1llo2 pro3gram was co4nceived early in 1960"

I guess I should use gsub maybe with perl = TRUE, but don't know how.

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

gsub( x = string, pattern = "(o)", replacement = "\\1 $count", perl = TRUE )
like image 246
Rasmus Larsen Avatar asked Dec 20 '22 06:12

Rasmus Larsen


1 Answers

Here's 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"))

Note: I maintain the pacman and qdapRegex packages.

like image 187
Tyler Rinker Avatar answered Jan 05 '23 07:01

Tyler Rinker