Reputation: 715
I have a vector of strings such as:
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\";")
I need to extract the quoted text (any characters) that follows gene_biotype. For example:
[1] protein_coding\
[2] IG_V_gene\
[3] protein_coding\
I have tried using str_extract in the stringr package, but I cannot get the regex to work.
Any help would be greatly appreciated!
Upvotes: 1
Views: 75
Reputation: 4534
I found this here
stringi::stri_extract_all_regex(x, '(?<=").*?(?=")')[[1]][1]
#[1] "protein_coding"
Upvotes: -1
Reputation: 206576
You can use a regular expression with some help from the stringr
package to get the data you need. For example
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"
This returns a matrix with the match and the category. If you just want the category you can do
str_match(x, "gene_biotype\\s+\"([^\"]+)\"")[,2]
# [1] "protein_coding" "IG_V_gene" "protein_coding"
Upvotes: 4