0

For example, function should be: function_name(phonenumber, n)

  • function_name(123-456-7890, 1) should return 123
  • function_name((123)-456-7890, 3) should return 7890
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 3
    What did you try? Where are you getting stuck? How many different number types do you need to match? Does this help give you a start: https://stackoverflow.com/questions/31172751/extracting-phone-number-issue-in-r – MrFlick Apr 26 '20 at 21:57
  • broncos24, you are welcome on SO, but you are starting to show a pattern that is not really aligned to the "norm" on StackOverflow (at least within [tag:r] channels). (1) Please *accept* answers (not just upvoting them). (2) Do some research on your own first, please do not treat "asking a question on SO" as your first web-search. (3) When you do ask a question, please provide (much) more than just terse requirements, including sample data, intended output, and the code you've attempted before now. You're very welcome here, but please respect our volunteered time. – r2evans Apr 27 '20 at 22:12

5 Answers5

3
function_name <- function(phone, n) Filter(nzchar, strsplit(phone, "\\D+")[[1]])[n]
function_name("123-456-7890", 1)
# [1] "123"
function_name("(123)-456-7890", 3)
# [1] "7890"
r2evans
  • 141,215
  • 6
  • 77
  • 149
3

One base R option is using regmatches

function_name <- function(phonenumber, n) regmatches(phonenumber,gregexpr("\\d+",phonenumber))[[1]][n]
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

We can split by - and then extract the 'nth' group

f1 <- function(phonenumber, n){
             setdiff(strsplit(phonenumber, '[[:punct:]]+')[[1]], "")[n]
    }

f1('123-456-7890', 3)
#[1] "7890"

f1('(123)-456-7890', 3)
#[1] "7890"
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You can either use \\w+ or \\d+ :

get_nth_group <- function(x, n) stringr::str_extract_all(x, '\\w+')[[1]][n]

get_nth_group("123-456-7890", 1)
#[1] "123"

get_nth_group("(123)-456-7890", 3)
#[1] "7890"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

I would suggest something like this:

library(tidyverse)

get_phone_group <- function(phonenum, n) {
  str_extract_all(phonenum, "\\d+", simplify = TRUE)[, n]
}

get_phone_group("123-456-7890", 1)
#> [1] "123"
get_phone_group("(123)-456-7890", 3)
#> [1] "7890"
get_phone_group(c("345-169-234", "(123)-456-7890"), 3)
#> [1] "234"  "7890"

Created on 2020-04-27 by the reprex package (v0.3.0)

Note that the resulting function is vectorized and therefore nice to use in e.g. a mutate context.

Peter H.
  • 1,995
  • 8
  • 26