Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify a substring matched by regex and place it back [duplicate]

Tags:

regex

r

I have an arbitrary string, say "1a2 2a1 3a2 10a5" I want to do an arbitrary mathematical operation, say doubling, to some of the numbers, say anything followed by an "a".

I can extract the numbers I want with relative ease

string = "1a2 2a1 3a2 10a5"
numbers = stringr::str_extract_all(string,'[0-9]+(?=a)')[[1]]

and obviously, doubling them is trivial

numbers = 2*(as.integer(numbers))

But I am having problems with placing the new results in their old positions. To get the output "2a2 4a1 6a2 20a5". I feel like there should be a single function that accomplishes this but all I can think of is recording the original indexes of the matches using gregexpr and manually placing the new results in the coordinates.

like image 622
OganM Avatar asked Dec 19 '25 21:12

OganM


1 Answers

We can use str_replace_all from stringr to capture numbers followed by "a" and then multiply them by 2 in their callback function.

stringr::str_replace_all(string, "\\d+(?=a)", function(m) as.integer(m) * 2)
#[1] "2a2 4a1 6a2 20a5"
like image 144
Ronak Shah Avatar answered Dec 21 '25 14:12

Ronak Shah