【问题标题】:How to keep only information inside a complex string in R?如何仅将信息保留在R中的复杂字符串中?
【发布时间】:2017-01-06 19:22:19
【问题描述】:

我想在一个复杂的字符串中保留一个字符串。我认为我可以使用正则表达式来保留我需要的东西。基本上,我只想在Function=\"SMAD5\" 中保留\"\" 之间的信息。我也想保留空字符串:Function=\"\"

df=structure(1:6, .Label = c("ID=Gfo_R000001;Source=ENST00000513418;Function=\"SMAD5\";", 
"ID=Gfo_R000002;Source=ENSTGUT00000017468;Function=\"CENPA\";", 
"ID=Gfo_R000003;Source=ENSGALT00000028134;Function=\"C1QL4\";", 
"ID=Gfo_R000004;Source=ENSTGUT00000015300;Function=\"\";", "ID=Gfo_R000005;Source=ENSTGUT00000019268;Function=\"\";", 
"ID=Gfo_R000006;Source=ENSTGUT00000019035;Function=\"\";"), class = "factor")

这应该是这样的:

"SMAD5"
"CENPA"
"C1QL4"
NA
NA
NA

到目前为止,我能做的:

gsub('.*Function=\"',"",df)

[1] "SMAD5\";" "CENPA\";" "C1QL4\";" "\";"      "\";"      "\";"     

但我被一堆\";" 困住了。如何用一行删除它们?

我试过这个:

gsub('.*Function=\"' & '.\"*',"",test)

但它给了我这个错误:

Error in ".*Function=\"" & ".\"*" : 
  operations are possible only for numeric, logical or complex types

【问题讨论】:

  • 试试gsub('.*Function=\"([^\"]*).*',"\\1",df)
  • 谢谢!成功了!

标签: r regex split gsub


【解决方案1】:

你可以使用

gsub(".*Function=\"([^\"]*).*","\\1",df)

regex demo

详情

  • .* - 任何 0+ 字符尽可能多,直到最后一个......
  • Function=\" - Function=" 子字符串
  • ([^\"]*) - 捕获组 1 匹配除 " 之外的 0+ 个字符
  • .* - 以及字符串的其余部分。

\1 是在结果中恢复组 1 内容的反向引用。

【讨论】:

    【解决方案2】:

    使用 stringr 我们也可以捕获组:

    library(stringr)
    matches <- str_match(df, ".*\"(.*)\".*")[,2]
    ifelse(matches=='', NA, matches)
    # [1] "SMAD5" "CENPA" "C1QL4" NA      NA      NA     
    

    【讨论】:

      【解决方案3】:

      使用rebus 可以更易读地构造正则表达式。

      rx <- 'Function="' %R% 
        capture(zero_or_more(negated_char_class('"')))
      

      然后,Wiktor 和 Sandipan 提到了匹配。

      rx <- 'Function="' %R% capture(zero_or_more(negated_char_class('"')))
      str_match(df, rx)
      stri_match_first_regex(df, rx)
      
      gsub(any_char(0, Inf) %R% rx %R% any_char(0, Inf), REF1, df)
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-20
      • 2022-01-17
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多