-1

How can I extract only six digit numbers in a string using R. I tried the following code. However, it returns the first digits encountered

as.numeric(gsub("([0-9]+).*$", "\1", x))

Example

56 NE. Vale Ave. Fullerton, CA 928311

The result should be

982311

  • The digits DO NOT always appear at the end of the string and could be placed anywhere in the string.
  • Multiple numbers can appear in the string. However, I'm fairly confident that there's only one six-digit number in it.
jonnyblue8
  • 109
  • 1
  • 8

1 Answers1

1

We can do

as.numeric(sub(".*([0-9]{6})$", "\\1", str1))
#[1] 928311

data

str1 <- "56 NE. Vale Ave. Fullerton, CA 928311"
akrun
  • 874,273
  • 37
  • 540
  • 662