R 根据模式删除字符串的一部分

R 根据模式删除字符串的一部分,r,R,我想知道如何找到一种模式来删除向量中每个字符串的某些部分 stri<-c("protein mono-ADP-ribosylation (GO:0140289)","negative regulation of viral life cycle (GO:1903901)","viral life cycle (GO:1901)") stri您可以尝试: gsub('\\s\\(.*', '', stri) 输出: [1] &q

我想知道如何找到一种模式来删除向量中每个字符串的某些部分

stri<-c("protein mono-ADP-ribosylation (GO:0140289)","negative regulation of viral life cycle (GO:1903901)","viral life cycle (GO:1901)")
stri您可以尝试:

gsub('\\s\\(.*', '', stri)
输出:

[1] "protein mono-ADP-ribosylation"           "negative regulation of viral life cycle" "viral life cycle" 
你可以试试:

gsub('\\s\\(.*', '', stri)
输出:

[1] "protein mono-ADP-ribosylation"           "negative regulation of viral life cycle" "viral life cycle" 

另一种方法你可以试试

library(stringr)
str_squish(str_replace(stri, "\\(.*\\)", ""))
# [1] "protein mono-ADP-ribosylation"           "negative regulation of viral life cycle"
# [3] "viral life cycle" 
  • \\(.\\)
    :匹配括号和括号内的所有内容
  • str_squish
    :减少字符串中重复的空白

您可以尝试的另一种方法

library(stringr)
str_squish(str_replace(stri, "\\(.*\\)", ""))
# [1] "protein mono-ADP-ribosylation"           "negative regulation of viral life cycle"
# [3] "viral life cycle" 
  • \\(.\\)
    :匹配括号和括号内的所有内容
  • str_squish
    :减少字符串中重复的空白