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

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -