Julien Massardier
Julien Massardier

Reputation: 1476

Match numbers in a string and add 1 to them in R

I need to increase the numbers following "abc" by 1 in a string

From: "abc1 + abc34 + def7"
To: "abc2 + abc35 + def7"

This failed attempt:

string <- "abc1 + abc34 + def7"
gsub("abc([0-9]+)","abc\\1\\+1",string)

Gave me this:

"abc1+1 + abc34+1 + def7"

Because the replacement is treated as a string, not as an expression.

It seems possible in Perl (perl example). Is it possible in R?

Upvotes: 0

Views: 785

Answers (2)

akuiper
akuiper

Reputation: 215057

You can use gsubfn; Capture abc and the digits after it, create a function as replacement where you can increase the matched digit by one and paste it with the captured abc:

library(gsubfn)
# here the first argument x is the first captured group, and y is the second captured group
gsubfn("(abc)(\\d+)", ~ paste(x, as.numeric(y) + 1, sep=""), string)
# [1] "abc2 + abc35 + def7"

Upvotes: 3

Neal Fultz
Neal Fultz

Reputation: 9687

You can set perl=TRUE and use regmatches to accomplish this, it's just a little ugly:

> m <- gregexpr('(?<=abc)[0-9]+', string, perl=TRUE)
> regmatches(string, m)
[[1]]
[1] "1"  "34"

> regmatches(string,m)[[1]] <- as.character(as.numeric(regmatches(string,m)[[1]]) + 1)
> string
[1] "abc2 + abc35 + def7

Upvotes: 3

Related Questions