[英]How to place the | symbol to match either of two regex patterns using stringr::str_match?
df$PlateName
中找到的不同格式為:
MIPS_AGRE_P01_DIL
MIPS_SSC_P50_DIL
MIPS_MtS_P34
MIPS_AT_P1_DIL
KORgex.mips.G12
MIPS_SSC_CL_P32_DIL
MIPS_SSC_CL_Low_DIL
使用此正則表達式非常笨拙,它會返回以下類型:
str_match(df$PlateName,
"MIPS_([:alnum:]+(?:_[:alnum:]+)?)_[Low|P:digit:]+(?:_[DIL])?|(KORgex).*")) %>%
as.tibble %>%
count(V2)
所有不適用的都是KORgex.mips.G12
類型。 如何使此正則表達式起作用?
AGRE 1654
AT 93
MtS 1324
SSC 5280
SSC_CL 288
NA 529
更新:
我意識到在這種情況下使用str_extract
可能更好,因為這只會返回df$PlateName
每個組件的匹配部分。
我仍然無法完全獲得返回所需信息的代碼-我缺少什么?
str_extract(data$PlateName, "[[:alnum:]+^(?!(MIPS))]_([[:alnum:]&&[^P]]+(_CL)?)?|(KORgex)") %>%
as.tibble %>%
count(value)`
返回:
KORgex 529
S_AGRE 1654
S_AT 93
S_MtS 1324
S_SSC 5280
S_SSC_CL 288
我一生都無法擺脫MIPS_
子類型中的S_
!
我們在這里可以做的最好的事情是使用分支重置組 (?|...|...)
僅獲得一個組,而不是多個組。
但是,R中的stringr
/ stringi
函數基於ICU regex風格 ,它不支持分支重置組。
在這里使用分支重置的最方便方法是通過grep
:
grep(df$PlateName,
"(?|MIPS_([:alnum:]+(?:_[:alnum:]+)?)_[Low|P:digit:]+(?:_[DIL])?|(KORgex).*)", perl=TRUE)
我認為這應該有效。 在與str_match
了一段時間之后,我決定使用str_replace
刪除不需要的所有內容會更容易。
df$PlateName %>%
str_replace("([[:alpha:]]+_)?([[:alpha:]]+)(_CL)?(_|\\.)??.*", "\\2\\3") %>%
as_tibble() %>%
count(value)
希望這可以幫助!
library(stringr)
library(dplyr)
#this step places "|" symbol to match either of two regex patterns
str_match(df$PlateName, "MIPS_(\\S+)_[P|Low].*|(KORgex).*") %>%
#convert to dataframe to count its occurrences
data.frame(stringsAsFactors=F) %>%
mutate(sub_PlateName = coalesce(X2, X3)) %>%
group_by(sub_PlateName) %>%
tally()
輸出為:
sub_PlateName n
1 AGRE 1
2 AT 1
3 KORgex 1
4 MtS 1
5 SSC 1
6 SSC_CL 2
樣本數據:
df <- structure(list(PlateName = c("MIPS_AGRE_P01_DIL", "MIPS_SSC_P50_DIL",
"MIPS_MtS_P34", "MIPS_AT_P1_DIL", "KORgex.mips.G12", "MIPS_SSC_CL_P32_DIL",
"MIPS_SSC_CL_Low_DIL")), .Names = "PlateName", class = "data.frame", row.names = c(NA,
-7L))
更新:使用str_extract
str_extract(df$PlateName, "(?<=MIPS_)\\S+(?=_P|_Low)|KORgex") %>%
as.tibble %>%
count(value)
# value n
#1 AGRE 1
#2 AT 1
#3 KORgex 1
#4 MtS 1
#5 SSC 1
#6 SSC_CL 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.