regular expression in R, reuse matched string in replacement

Viewed 231

I want to insert a '0' before the single digit month (e.g. 2020M6 to 2020M06) using regular expressions. The one below correctly matches the string I need to replace (a single digit at the end of the string following a 'M', excluding 'M'), but the replacement pattern '0$0' is interepreted literally in R; elsewhere (regeprep in matlab) I referenced the matched string, '6' in the example, by '$0'.

sub('(?<=M)([0-9]{1})$','0$0', c('2020M6','2020M10'), perl = T)
[1] "2020M0$0" "2020M10"

I cannot find how to reference and re-use matched strings in the replacement pattern.

PS: There are alternative ways to accomplish the task, but I need to use regular expressions.

2 Answers

Unfortunately, it is not possible to use a backreference to the whole match in base R regex functions.

You can use

sub("(M)([0-9])$", "\\10\\2", x)

With TRE regex like here, you do not have to worry about a digit after a backreference, since only 9 backreferences starting with 1 till 9 are allowed in TRE regex patterns. What is of interest is that you may use perl=TRUE in the above line of code and it will yield the same results.

See the R demo online:

x <-  c('2020M6','2020M10')
sub("(M)([0-9])$", "\\10\\2", x)
## => [1] "2020M06" "2020M10"

Also, see the regex demo.

I think you have to capture the digit after 'M' and not 'M' itself, therefore :

sub('(?<=M)([0-9]{1})$','0\\1', c('2020M6','2020M10'), perl = T)

Captured strings can be reused with \\1, \\2 etc, by the way.

Related