Chi Pak Chi Pak - 1 month ago 13
R Question

replace last number in string using regex

I want to replace the last number in a string using


S <- "abcd2efghi2.txt"

The last number and the position of the last number can vary.

So I've tried the regex

gsub("?<=[\d+])\b", "", S)

but that doesn't seem to work

Appreciate any help.

Answer Source

You can achieve that with a default TRE engine using the following regex:


Replace with the \1 backreference.


  • \d+ - 1 or more digits
  • (\D*) - Capturing group 1: any 0+ non-digit symbols
  • $ - end of string
  • \1 - a backreference to the Group 1 value (so as to restore the text matched and consumed with the (\D*) subpattern).

See the regex demo.

R code demo:

sub("\\d+(\\D*)$", "\\1", S)
## => [1] "abcd2efghi.txt"