【问题标题】:Extract a string of words between multiple specific words in R在R中的多个特定单词之间提取一串单词
【发布时间】:2020-02-17 05:15:10
【问题描述】:

我有一个包含一个或多个关键字的长字符串,在本例中为“Realm”。我一直在使用 gsub,但这只需要最后一个关键字之后的单词。

所以字符串看起来像:

...Attributes \r\n Realm - Afrotropical \r\n IUCN Ecosystem -- Terrestrial biome...

...Attributes \r\n Realm - Afrotropical \r\n Realm - Neotropical \r\n . IUCN Ecosystem -- Terrestrial biome...

我一直在使用该功能:

Realm_fun<-function(x){gsub('^.*Realm -\\s*|\\s*IUCN Ecosystem.*$', '', x)}

然后使用lapply 在所有字符串上进行有趣的操作。

我该怎么做才能获得Afrotropical 的第一个字符串和Afrotropical , Neotropical 的第二个?

【问题讨论】:

    标签: r lapply gsub


    【解决方案1】:

    我不知道你到底需要什么词。但一个想法可能是:

      regmatches(st, gregexpr("Realm - \\K(\\w+)",st,perl = TRUE))
    [[1]]
    [1] "Afrotropical"
    
    [[2]]
    [1] "Afrotropical" "Neotropical" 
    

    如果不想拆分的话:

    trimws(gsub("(?m)^.*Realm - (\\w+)|((?!Realm).)*$","\\1 ",st,perl=TRUE))
    
    [1] "Afrotropical"                "Afrotropical  \nNeotropical"
    
    gsub("(?m)^(?:(?!Real).)*$|[\r\n]|.*Realm - ","",st, perl = TRUE)
    
    [1] "Afrotropical  "              "Afrotropical  Neotropical  "
    

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      stringi::stri_extract_last(st, regex='(?<=Realm - )(\\w+)')
      

      stri_extract_last 将提取正则表达式的最后一个匹配项,使用查看断言断言我们可以收集单词然后环顾四周(在这种情况下使用正面查看),在这种情况下,您有单词 Afrotropical 和 新热带,然后是 Realm -

      如果你想提取最后一个匹配的两个字符串,你可以试试下面(stri_extract_all):

      stringi::stri_extract_all(st, regex='(?<=Realm - )(\\w+)')
      

      输入

      st <- c("...Attributes  \r\n      Realm - Afrotropical  \r\n  IUCN Ecosystem -- Terrestrial biome...", 
      "...Attributes  \r\n      Realm - Afrotropical  \r\n   Realm - Neotropical  \r\n .  IUCN Ecosystem -- Terrestrial biome..."
      )
      

      输出

      > stringi::stri_extract_last(st, regex='(?<=Realm - )(\\w+)')
      [1] "Afrotropical" "Neotropical" 
      
      
      > stringi::stri_extract_all(st, regex='(?<=Realm - )(\\w+)')
      [[1]]
      [1] "Afrotropical"
      
      [[2]]
      [1] "Afrotropical" "Neotropical" 
      

      【讨论】:

        【解决方案3】:

        使用基本函数gregexprregmatches

        library(magrittr)
        
        test<-c("...Attributes  \r\n      Realm - Afrotropical  \r\n  IUCN Ecosystem -- Terrestrial biome...","...Attributes  \r\n      Realm - Afrotropical  \r\n   Realm - Neotropical  \r\n .  IUCN Ecosystem -- Terrestrial biome...")
        
        test %>% gregexpr("(?<=(Realm - ))[a-zA-Z]+", ., perl = T) %>% regmatches(x = test) 
        
        #[[1]]
        #[1] "Afrotropical"
        
        #[[2]]
        #[1] "Afrotropical" "Neotropical"                                                         
        

        【讨论】:

          猜你喜欢
          • 2021-07-07
          • 1970-01-01
          • 2021-08-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-31
          • 2021-12-31
          • 1970-01-01
          相关资源
          最近更新 更多