【问题标题】:Returning text between a starting and ending regular expression返回开始和结束正则表达式之间的文本
【发布时间】:2019-03-06 21:11:25
【问题描述】:

我正在研究一个正则表达式,以从从报纸数据库下载的文件中提取一些文本。这些文件大部分格式正确。但是,每篇文章的全文都以定义明确的短语^Full text: 开头。但是,全文的结尾没有划定。我能想到的最好的结果是全文以各种元数据标签结尾,如下所示:Subject: , CREDIT:, Credit

所以,我当然可以开始这篇文章了。但是,我很难找到一种方法来选择全文开头和结尾之间的文本。

这因两个因素而变得复杂。首先,显然结尾字符串会有所不同,尽管我觉得我可以选择类似: `^[:alnum:]{5,}: ' 这样就可以捕捉到结尾。但另一个复杂的因素是,在全文开始之前出现了类似的标签。如何让 R 只返回全文正则表达式和结尾正则表达式之间的文本

test<-c('Document 1', 'Article title', 'Author: Author Name', 'https://a/url', 'Abstract: none', 'Full text: some article text that I need to capture','the second line of the article that I need to capture', 'Subject: A subject', 'Publication: Publication', 'Location: A country')

test2<-c('Document 2', 'Article title', 'Author: Author Name', 'https://a/url', 'Abstract: none', 'Full text: some article text that I need to capture','the second line of the article that I need to capture', 'Credit: A subject', 'Publication: Publication', 'Location: A country')

我目前的尝试在这里:

test[(grep('Full text:', test)+1):grep('^[:alnum:]{5,}: ', test)]

谢谢。

【问题讨论】:

    标签: r regex stringr


    【解决方案1】:

    这只是搜索匹配'Full text:'的元素,然后搜索匹配':'之后的下一个元素

    get_text <- function(x){
      start <- grep('Full text:', x)
      end <- grep(':', x) 
      end <- end[which(end > start)[1]] - 1
      x[start:end]
    }
    
    get_text(test)
    # [1] "Full text: some article text that I need to capture"  
    # [2] "the second line of the article that I need to capture"
    get_text(test2)
    # [1] "Full text: some article text that I need to capture"  
    # [2] "the second line of the article that I need to capture"
    

    【讨论】:

      猜你喜欢
      • 2014-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      相关资源
      最近更新 更多