【问题标题】:R grep() return whole matching line (similar to the unix grep -A -B?)R grep() 返回整个匹配行(类似于 unix grep -A -B?)
【发布时间】:2022-01-16 18:30:53
【问题描述】:

我一直在寻找一种方法来让 grep 返回一整行以匹配模式。 R 的 grep() 中是否有此功能?我想像unix grep arguments -An

一些上下文:对于我写的一篇论文,我想创建一个数据表或论文中所有引用的向量。使用qdapRegex::rm_round() 提取论文中括号内的所有内容有时只返回一年(在引用的情况下,如:'As put by Smith (2020)')。抓住整个句子而不是仅仅'2020'会很好。

有什么想法吗?谢谢!

【问题讨论】:

  • 当然,这很简单,具体取决于您的输入数据。您能分享示例数据和您的预期结果吗?

标签: r


【解决方案1】:

grep 有一个参数 value,您可以将其设置为 TRUE 以获取整个字符串。

考虑这个您正在寻找数字的示例。

x <- c('This is 2022', 'This is not a year', '2021 was last year')
grep('\\d+', x)
#[1] 1 3

默认情况下,grep 返回找到匹配项的索引。

如果您需要完整的字符串作为输出 -

grep('\\d+', x, value = TRUE)
#[1] "This is 2022"       "2021 was last year" 

【讨论】:

  • 太好了,我会尝试使用这个!我肯定误解了 value 参数的功能。感谢您对此的澄清。
【解决方案2】:
s <- c("As put forth by Smith (2020)",
       "As put forth by Smith 2020",
       "As put forth by Smith",
       "As put forth (Smith 2020)")

s[grep(pattern = "\\(.*\\)", x = s)]
#> [1] "As put forth by Smith (2020)" "As put forth (Smith 2020)"

Created on 2022-01-14 by the reprex package (v2.0.1)

【讨论】:

    猜你喜欢
    • 2017-06-03
    • 2019-01-12
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2012-09-30
    相关资源
    最近更新 更多