【问题标题】:In R, gsub & Regex lookahead or lookbehind expression to remove everything BEFORE a string pattern?在 R、gsub 和 Regex 前瞻或后向表达式中删除字符串模式之前的所有内容?
【发布时间】:2015-11-16 07:20:10
【问题描述】:

在 R 中,我有一个包含一列的数据框,其中每一行都有重复的文本,我想删除与特定模式匹配的重复文本:

x <- c("DOI: 10.5256/f1000research.6541.r7660 The revised article answers most of my remarks and questions in a ... Continue reading The revised article answers most of my remarks and questions in a satisfactory way.", 
"DOI: 10.5256/f1000research.6601.r7701 The revision ... Continue reading The revision is approved I have read this", 
"DOI: 10.5256/f1000research.6599.r7859 I have read the revised article by Horrell and D'Orazio. They have responded appropriately to ... Continue reading I have read the revised article by Horrell and D'Orazio. They have responded appropriately to the concerns/questions raised")

我可以使用什么函数来删除... Continue readingContinue reading 之前的所有内容,包括... Continue readingContinue reading

【问题讨论】:

  • 你的字符串可以包含换行符吗?见this demo。使用 gsub("^[\\s\\S]*[.]{3}\\s*Continue reading\\s*", "", x, perl=T) 之类的东西。

标签: regex r gsub regex-lookarounds


【解决方案1】:

这应该删除Continue reading之前的所有内容

sub('.*\\.{3}\\s*(Continue reading.*)$', '\\1', x)

如果需要删除... Continue reading之前的字符

sub('.*(\\.{3}\\s*Continue reading.*)$', '\\1', x)

【讨论】:

    【解决方案2】:

    使用子

    包括继续阅读,

    sub(".*Continue reading", "", x)
    

    不包括继续阅读。

    sub(".*(?=\\bContinue reading)", "", x, perl=TRUE)
    

    sub(".*\\b(Continue reading)", "\\1", x)
    

    【讨论】:

      猜你喜欢
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多