R regex在特定位置的字符之间获取字符串

时间:2015-06-24 18:50:34

标签: regex r gsub

我在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

我想在out中使用DT$GKTgsubregex获取输出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

我尝试了gsub(x=DT$GKT, pattern = "(:)(.*)(, |\\b)", replacement=""),但它只获取了第一个实例。

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

3 个答案:

答案 0 :(得分:7)

使用gsub的另一个选项是使用后面的

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

答案 1 :(得分:4)

修改

您可以使用以下正则表达式替换...

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

答案 2 :(得分:2)

您可以使用前瞻(?=)来检查:并仅捕获第一组

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"