【问题标题】:How to extract text from a string using a regular expression in R?如何使用 R 中的正则表达式从字符串中提取文本?
【发布时间】:2019-04-15 17:17:07
【问题描述】:

我有一个字符串向量,例如:

x <- c("gene_biotype \"protein_coding\"; transcript_name \"IGHV3-66-201\"; 
transcript_source \"havana\"; transcript_biotype \"IG_V_gene\"; 
protein_id \"ENSP00000375041\"; protein_version \"2\"; tag 
\"cds_end_NF\"; tag \"mRNA_end_NF\"; tag \"basic\"; 
transcript_support_level \"NA\";",
"gene_id \"ENSG00000211973\"; gene_version \"2\"; transcript_id 
\"ENST00000390633\"; transcript_version \"2\"; exon_number \"1\"; 
gene_name \"IGHV1-69\"; gene_source \"ensembl_havana\"; gene_biotype 
\"IG_V_gene\"; transcript_name \"IGHV1-69-201\"; transcript_source 
\"ensembl_havana\"; transcript_biotype \"IG_V_gene\"; protein_id 
\"ENSP00000375042\"; protein_version \"2\"; tag \"cds_end_NF\"; tag 
\"mRNA_end_NF\"; tag \"basic\"; transcript_support_level \"NA\";",
"gene_id \"ENSG00000211973\"; gene_version \"2\"; transcript_id 
\"ENST00000390633\"; transcript_version \"2\"; exon_number \"2\"; 
gene_name \"IGHV1-69\"; gene_source \"ensembl_havana\"; gene_biotype 
\"protein_coding\";")

我需要提取gene_biotype 后面的引用文本(任何字符)。例如:

[1] protein_coding\ 
[2] IG_V_gene\
[3] protein_coding\

我尝试在 stringr 包中使用 str_extract,但我无法让正则表达式工作。

任何帮助将不胜感激!

【问题讨论】:

    标签: r regex


    【解决方案1】:

    您可以在stringr 包的帮助下使用正则表达式来获取您需要的数据。例如

    library(stringr)
    str_match(x, "gene_biotype\\s+\"([^\"]+)\"")
    #      [,1]                                [,2]            
    # [1,] "gene_biotype \"protein_coding\""   "protein_coding"
    # [2,] "gene_biotype \n\"IG_V_gene\""      "IG_V_gene"     
    # [3,] "gene_biotype \n\"protein_coding\"" "protein_coding"
    

    这将返回一个包含匹配项和类别的矩阵。如果你只想要你可以做的类别

    str_match(x, "gene_biotype\\s+\"([^\"]+)\"")[,2]
    # [1] "protein_coding" "IG_V_gene"      "protein_coding"
    

    【讨论】:

      【解决方案2】:

      我找到了这个here

      stringi::stri_extract_all_regex(x, '(?<=").*?(?=")')[[1]][1]
      #[1] "protein_coding"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多