r - replace last number in string using regex -


i want replace last number in string using regex , gsub

s <- "abcd2efghi2.txt" 

the last number , position of last number can vary.

so i've tried regex

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

but doesn't seem work

appreciate help.

you can achieve default tre engine using following regex:

\d+(\d*)$ 

replace \1 backreference.

details

  • \d+ - 1 or more digits
  • (\d*) - capturing group 1: 0+ non-digit symbols
  • $ - end of string
  • \1 - backreference group 1 value (so restore text matched , consumed (\d*) subpattern).

see regex demo.

r code demo:

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

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -