Extract a character from a filename +1 character

Viewed 59

I want to be able to extract a character from a filename. I want to extract B+1 character

df <- c("2010-01-14_B1_RP_NEG_09.mzML","2010-01-14_B1_RP_NEG_10.mzML","2010-01-15_B2_RP_NEG_11.mzML","2010-01-15_B2_RP_NEG_12.mzML", "2010-01-16_B3_RP_NEG_13.mzML", "2010-01-16_B3_RP_NEG_14.mzML")
df

It could be done by:

substring(df,12,13)

But in a long filename it would eb convenient to know how to extract B+1 character. This code extract the characters after B.

substring(df, regexpr("B", df)+1)

It should look like

B1, B1, B2, B2, B3, B3

Any good suggestions?:)

2 Answers

Using sub we can extract "B" followed by a number.

sub(".*(B\\d+).*", "\\1", df)
#[1] "B1" "B1" "B2" "B2" "B3" "B3"

Or with str_extract :

stringr::str_extract(df, "B\\d+")

We can use substr with trimws in base R

substr(trimws(df, whitespace = '^[^_]+_'), 1, 2)
#[1] "B1" "B1" "B2" "B2" "B3" "B3"
Related