0

Trying to use StringR to find all the digits which occur at the end of the text.

For example

x <- c("Africa-123-Ghana-2", "Oceania-123-Sydney-200")

and StringR operation should return

"2  200"

I believe there might be multiple methods, but what would be the best code for this?

Thanks.

neilfws
  • 32,751
  • 5
  • 50
  • 63
mike
  • 49
  • 4

2 Answers2

2

You could use

sub(".*-(\\d+)$", "\\1", x)
#[1] "2"   "200"

Or

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

Or

stringi::stri_extract_last_regex(x, "\\d+")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

We can use regexpr/regmatches in base R to match one or more digits (\\d+) at the end ($) of the string

regmatches(x, regexpr("\\d+$", x))
#[1] "2"   "200"

Or with sub, we match characters until the last character that is not a digit and replace with blank ("")

sub(".*\\D+", "", x)
#[1] "2"   "200"

Or using strsplit

sapply(strsplit(x, "-"), tail, 1)
#[1] "2"   "200"

Or using stringr with str_match

library(stringr)
str_match(x, "(\\d+)$")[,1]
#[1] "2"   "200"

Or with str_remove

str_remove(x, ".*\\D+")
#[1] "2"   "200"
akrun
  • 874,273
  • 37
  • 540
  • 662