Extract characters from string based on rule (repeated hyphen)

Viewed 44

I have a large dataframe with a column that looks something like this:

var <- c("150507-001-0000001", "KMD070515-2-0000001", 
"15144KMD01AA-0000001", "Z75Z151222-0000001")

What I want to do is extract part of the string. I want all characters undtil second hyphen. So this is what I need:

150507-001
KMD070515-2 
15144KMD01AA-0000001
Z75Z151222-0000001

So I know if I only wanted the data before the hyphen I'd do this:

> var <- sub("-.*", "", var)

> var

150507
KMD070515 
15144KMD01AA
Z75Z151222

I've also tried a package qdap which kinda gave me what I wanted:

library("qdap")
var <- beg2char(var, "-", 2)

I do get the column I need with the last code, however something seems to be wrong. Because when I do a left_join based on the column it doesn't work. I can find a match by copy-paste in data view, but left_join doesn't find anything. Doing a leftjoin with the var made with sub (see above) do however work. But for some of my rows I need the characters after the first hyphen (and before the second) to find a match.

2 Answers

We can use sub to match the pattern of characters that are not a - followed by - and another set of characters that are not a -, capture as a group ((...)) and replace with the backreference (\\1) of the captured group

sub("^([^-]+-[^-]+).*", "\\1", var)
#[1] "150507-001"           "KMD070515-2"         
#[3]  "15144KMD01AA-0000001" "Z75Z151222-0000001"  

Here is a non regex solution, for those who might be interested:

x <- "150507-001-0000001"
paste(strsplit(x, "-")[[1]][1:2], collapse="-")

[1] "150507-001"

If you wanted to apply this logic to your entire vector, then use:

sapply(var, function(x) paste(strsplit(x, "-")[[1]][1:2], collapse="-"))
Related