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

regex
and
gsub


S <- "abcd2efghi2.txt"


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

So I've tried the regex

?<=[\d+])\b
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:

\d+(\D*)$

Replace with the \1 backreference.

Details

  • \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"