Extract number immediately after substring, ignoring spaces and non-alphanumeric

Viewed 35

I've got some tweet data that looks like text

WR 198  CM 23  SPIN 34

WR:22 CM:7 SPIN:0

WR 96 CM 17 SPIN 8

WR:82 CM:9 SPIN:10

WR - 206
CM - 38
SPIN - 18

WR - 140
CM - 18
Spin - 12

WR 62  CM 11  SPIN  4

WR-
CM-
Spin_

WR - 67
CM - 18
Spin - 5

WR 38 CM 2 SPIN 0

The tweets usually have the same sort of structure: WR/CM/SPIN (in various cases), followed by a space or non-alphanumeric character and then a number. I'm interested in writing a function which takes as arguments the text and one of WR/CM/Spin and returns the associated number.

Here are some desired inputs and outputs for the function, f.

f("WR 198  CM 23  SPIN 34", 'WR')
198
f("WR 198  CM 23  SPIN 34", 'CM')
23
f("SPIN - 18", 'SPIN')
18
f("WR:82 CM:9 SPIN:10", "WR")
82

Can I achieve this with stringr::str_extract? If so, what is the proper regex?

1 Answers

There might be a more sophisticated solution using just one str_extract statement, but you could use:

library(stringr)

my_function <- function(input_string, target) {
  
  str_extract(input_string, paste0(target, "\\D*\\d+")) |> str_extract("\\d+")
  
}

This returns

my_function("WR 198  CM 23  SPIN 34", 'WR')
#> [1] "198"
my_function("WR 198  CM 23  SPIN 34", 'CM')
#> [1] "23"
my_function("SPIN - 18", 'SPIN')
#> [1] "18"
my_function("WR:82 CM:9 SPIN:10", "WR")
#> [1] "82"
Related