2

Given the following vector:

v = c("A/5 21171", "PC 175959", "STON/O2. 3101282", "113803", "373450")

How can extract the last 5 or 6 digits from each element? This the desired output:

v_processed = c("21171", "175959", "3101282", "113803", "373450")

My try:

v = unlist(strsplit(v, "^[^0-9]+"))
v[v == ""] = NA
v_processed = na.omit(v)

But that last snippet gives me this:

"5 21171"    "175959"     "2. 3101282" "113803"     "373450" 

I do not want that 5 in the first element, nor the "2." in the third one.

Thx.

2
  • Wait, 3101282 is 7 digits. And try sub(".*?(\\d{5,6})$", "\\1", v) (if you want 101282 in fact, not 3101282) Commented Apr 28, 2017 at 8:07
  • You are right. 3101282 is 7 digits. Then I refer to the last bunch of digits, no matter they are 5, 6 or 7 Commented Apr 28, 2017 at 8:09

2 Answers 2

2

You may use

> sub(".*\\b(\\d+)$", "\\1", v)
[1] "21171"   "175959"  "3101282" "113803"  "373450" 

Here, .*\\b matches all the chars up to the last leading word boundary and grabs 1+ digits at the end of the string with (\\d+)$ into Group 1.

Or, if the digits are preceded with whitespace:

> sub(".*\\s(\\d+)$", "\\1", v)
[1] "21171"   "175959"  "3101282" "113803"  "373450" 

where .*\\s matches the string up to the last whitespace.

Alternatively, use a matching approach. Here is how you may extract 1+ digits (as a whole word) at the end of the string:

> regmatches(v, regexpr("\\b\\d+$", v))
[1] "21171"   "175959"  "3101282" "113803"  "373450"

Or extract them only if they are preceded with whitespace:

> regmatches(v, regexpr("(?<!\\S)\\d+$", v, perl=TRUE))
[1] "21171"   "175959"  "3101282" "113803"  "373450" 

Here, a PCRE regex (see perl=TRUE) is used to simplify the code. The (?<!\\S) is a negative lookbehind that makes sure there is no non-whitespace symbol immediately to the left of the current location.

1

We can use substring

substring(v, nchar(v)-c(4, 5, 6, 5, 5), nchar(v))
#[1] "21171"   "175959"  "3101282" "113803"  "373450"

Or with str_extract

library(stringr)
str_extract(v, "\\d+$")
#[1] "21171"   "175959"  "3101282" "113803"  "373450" 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.