R regex to fetch strings between characters at specific positions

113 views Asked by At

I have some string data as follows in R.

DT <- structure(list(ID = c(1, 2, 3, 4, 5, 6), GKT = c("G1:GRST, G45:KRPT", 
"G48932:KD56", "G7764:MGI45, K7786:IRE4R, K45:TG45", "K4512:3345, G51:56:34, K22:45I67", 
"K678:RT,IG, G123:TGIF, G33:IG56", "T4534:K456")), .Names = c("ID", 
"GKT"), class = "data.frame", row.names = c(NA, 6L))

DT
  ID                                GKT
1  1                  G1:GRST, G45:KRPT
2  2                        G48932:KD56
3  3 G7764:MGI45, K7786:IRE4R, K45:TG45
4  4   K4512:3345, G51:56:34, K22:45I67
5  5    K678:RT,IG, G123:TGIF, G33:IG56
6  6                         T4534:K456

I want to get the output out from DT$GKT using gsub and regex in R.

out <- c("G1, G45", "G48932", "G7764, K7786, K45", "K4512, G51, K22", 
"K678, G123, G33", "T4534")
DT$out <- out
DT
  ID                                GKT               out
1  1                  G1:GRST, G45:KRPT           G1, G45
2  2                        G48932:KD56            G48932
3  3 G7764:MGI45, K7786:IRE4R, K45:TG45 G7764, K7786, K45
4  4   K4512:3345, G51:56:34, K22:45I67   K4512, G51, K22
5  5    K678:RT,IG, G123:TGIF, G33:IG56   K678, G123, G33
6  6                         T4534:K456             T4534

I have tried gsub(x=DT$GKT, pattern = "(:)(.*)(, |\\b)", replacement=""), but it fetches only first instances.

gsub(x=DT$GKT, pattern = "(:)(.*)(, |\\b)", replacement="")
[1] "G1"     "G48932" "G7764"  "K4512"  "K678"   "T4534" 
3

There are 3 answers

0
hwnd On BEST ANSWER

EDIT

You can use the following regular expression for replacing ...

DT$out <- gsub(':\\S+\\b', '', DT$GKT)
DT

#   ID                                GKT               out
# 1  1                  G1:GRST, G45:KRPT           G1, G45
# 2  2                        G48932:KD56            G48932
# 3  3 G7764:MGI45, K7786:IRE4R, K45:TG45 G7764, K7786, K45
# 4  4   K4512:3345, G51:56:34, K22:45I67   K4512, G51, K22
# 5  5    K678:RT,IG, G123:TGIF, G33:IG56   K678, G123, G33
# 6  6                         T4534:K456             T4534
0
Rorschach On

You could use a lookahead (?=) to check for : and capture just the first group

unlist(regmatches(DT$GKT, gregexpr("([A-Z0-9]+)(?=:)", DT$GKT, perl=T)))

# [1] "G1"     "G45"    "G48932" "G7764"  "K7786"  "K45"    "K4512"  "G51"   
# [9] "56"     "K22"    "K678"   "G123"   "G33"    "T4534" 
0
David Arenburg On

Another option using gsub is to use a look behind

DT$out <- gsub("(?=:)(.[A-Z0-9,]+)(?=\\b)", "", DT$GKT, perl = TRUE)
DT
#   ID                                GKT               out
# 1  1                  G1:GRST, G45:KRPT           G1, G45
# 2  2                        G48932:KD56            G48932
# 3  3 G7764:MGI45, K7786:IRE4R, K45:TG45 G7764, K7786, K45
# 4  4   K4512:3345, G51:56:34, K22:45I67   K4512, G51, K22
# 5  5    K678:RT,IG, G123:TGIF, G33:IG56   K678, G123, G33
# 6  6                         T4534:K456             T4534