For example, function should be: function_name(phonenumber, n)
function_name(123-456-7890, 1)
should return 123function_name((123)-456-7890, 3)
should return 7890
For example, function should be: function_name(phonenumber, n)
function_name(123-456-7890, 1)
should return 123function_name((123)-456-7890, 3)
should return 7890function_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"
One base R option is using regmatches
function_name <- function(phonenumber, n) regmatches(phonenumber,gregexpr("\\d+",phonenumber))[[1]][n]
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"
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"
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.