Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract numbers that appear last in the string

Tags:

r

Is there a way to extract numbers from the strings that appear last

asd <- c("asdf sfsfsd54 sdfsdfsdf sdfsdfsf654")
asd1 <- c("asdf sfsfsd54 sdfsdfsdf sdfsdfsf65421")

Expected output

new_asd 
654

new_asd1
65421
like image 478
manu p Avatar asked Oct 26 '25 03:10

manu p


2 Answers

A single regex is sufficient for your situation.

stringr::str_extract(asd, "(\\d+$)")

The $ anchors the capture group to the end of the string.

like image 79
Michael Dewar Avatar answered Oct 27 '25 18:10

Michael Dewar


This code extracts always the last numeric entries in a string:

(stringr::str_extract(asd, stringr::regex("(\\d+)(?!.*\\d)")))
"654"
(stringr::str_extract(asd1, stringr::regex("(\\d+)(?!.*\\d)")))
"65421"

If you want to get only the number when the very last character of the string is a number then you could implement a simple ifelse condition to check for that specifically, e.g.:

x<- c("asdf sfsfsd54 sdfsdfsdf sdfsdfsf654f")
ifelse(!is.na(as.numeric(substr(x, nchar(x), nchar(x)))), 
       (stringr::str_extract(x, stringr::regex("(\\d+)(?!.*\\d)"))),
       NA)
NA #returns NA because last entry of string is not numeric ("f")
like image 44
JKupzig Avatar answered Oct 27 '25 17:10

JKupzig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!