Export multiple matching pattern

Viewed 70

I am trying to extract AOB1 or AOB2 or AOB3 from the string below.

df <- data.frame(
  id = c(1,2,3),
  string = c("acv-32-AOB1", "osa-122-AOB2","cds-543-rr-AOB3")
)

> df
  id          string
1  1     acv-32-AOB1
2  2    osa-122-AOB2
3  3 cds-543-rr-AOB3

Any ideas?

Thanks!

4 Answers

We can use trimws from base R

trimws(df$string, whitespace =".*-")
[1] "AOB1" "AOB2" "AOB3"

Or use sub from base R

sub(".*-", "", df$string)
[1] "AOB1" "AOB2" "AOB3"

Or if we need to do extract the 'AOB' followed by digits

library(stringr)
str_extract(df$string, "AOB\\d+")
[1] "AOB1" "AOB2" "AOB3"

You can use regular expressions for this:

  1. .* Match anything
  2. (AOB[1-3]) then match AOB followed by a 1, 2 or 3
  3. \\1 replace the entire string with the matched AOB1-3 slot
gsub(".*(AOB[1-3])", "\\1", df$string)

I made some modification so that your desired pattern could be everywhere and you could use the following solution to extract it:

df$res <- gsub("(.*)?([A-Z]{3}\\d)(.*)?", "\\2", df$string, perl = TRUE)
df

  id          string  res
1  1     acv-32-AOB1 AOB1
2  2    osa-122-AOB2 AOB2
3  3 cds-543-rr-AOB3 AOB3

Here is one more dear friends:

m <- gregexpr("[a-zA-Z]{3}\\d{1}", df$string)

unlist(regmatches(df$string, m))
> unlist(regmatches(df$string, m))
[1] "AOB1" "AOB2" "AOB3"
Related