[英]R:how to extract the exact character between two characters for a vector
dat1 <- c('human(display_long)|uniprotkb:ESR1(gene name)')
dat2 <- c('human(display_long)|uniprotkb:TP53(gene name)')
dat3 <- c('human(display_long)|uniprotkb:GPX4(gene name)')
dat4 <- c('human(display_long)|uniprotkb:ALOX15(gene name)')
dat5 <- c('human(display_long)|uniprotkb:PGR(gene name)')
dat <- c(dat1,dat2,dat3,dat4,dat5)
如何提取載體 dat 的 'human(display_long)|uniprotkb:' 和 '(gene name)' 之間的基因名稱。謝謝!
您可以使用regexpr
和regmatches
提取human(display_long)|uniprotkb:
和(gene name)
之間的文本。
regmatches(dat
, regexpr("(?<=human\\(display_long\\)\\|uniprotkb:).*(?=\\(gene name\\))"
, dat, perl=TRUE))
#[1] "ESR1" "TP53" "GPX4" "ALOX15" "PGR"
其中(?<=human\\\\(display_long\\\\)\\\\|uniprotkb:)
是對human(display_long)|uniprotkb:
的正面展望,而(?=\\\\(gene name\\\\)
是對human(display_long)|uniprotkb:
的正面展望(gene name)
和.*
是中間的文本。
另一種方法是使用sub
但如果沒有匹配,這可能會失敗。
sub(".*human\\(display_long\\)\\|uniprotkb:(.*)\\(gene name\\).*", "\\1", dat)
#[1] "ESR1" "TP53" "GPX4" "ALOX15" "PGR"
其他不搜索完整模式的方法可能是:
regmatches(dat, regexpr("(?<=:)[^(]*", dat, perl=TRUE))
sub(".*:([^(]*).*", "\\1", dat)
sub(".*:(.*)\\(.*", "\\1", dat)
您可以嘗試使用此正則表達式,它將提取'uniprotkb'
和'uniprotkb'
括號 ( (
) 之間的文本。
sub('.*uniprotkb:(\\w+)\\(.*', '\\1', dat)
#[1] "ESR1" "TP53" "GPX4" "ALOX15" "PGR"
使用stringr
並查看后面你可以試試這個:
library(stringr)
str_extract(dat, "(?<=:)[A-z0-9]+")
#[1] "ESR1" "TP53" "GPX4" "ALOX15" "PGR"
假設在基因名稱之前只有一個冒號。
我們可以使用str_remove_all
library(stringr)
str_remove_all(dat, ".*uniprotkb:|\\(.*")
[1] "ESR1" "TP53" "GPX4" "ALOX15" "PGR"
或者使用來自base R
trimws
trimws(dat, whitespace = ".*uniprotkb:|\\(.*")
[1] "ESR1" "TP53" "GPX4" "ALOX15" "PGR"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.