【问题标题】:Regex in R select sentence ending in new lineR中的正则表达式选择以新行结尾的句子
【发布时间】:2016-11-06 23:14:52
【问题描述】:

我的理解是 R 使用扩展正则表达式或类似 Perl 的正则表达式。我已经在 SO 和网络上搜索了这个正则表达式问题的解决方案,但我发现是空的:

在 R 中,我有一个文本文件向量。每个元素由几个段落组成。我想从每个元素中提取几句话来用这个文本子集创建一个新向量。我要提取的句子遵循可预测的模式。

text <- c("AND \n \n house notes: text text/text.\n \n text text \n text",
          "AND \n \n notes: text text/text.\n \n text text \n text",
          "AND \n \n house: text text/text.\n \n text text \n text")

我想提取“house notes”、“house”或“notes”与第一个“\n”之间的所有文本。 “house notes”、“house”或“notes”这些词可能在文档中的其他位置,但我对它们的第一次出现感兴趣。

> output
"house notes: text text/text.\n",
"notes: text text/text.\n ",
"house: text text/text.\n "

我可以让它在 php \w++ notes: \w++ \w*+[^_]\w[^:\\]*+\\\w 但不是 R.

【问题讨论】:

  • gsub('\n ([^\n]+:[^\n]+)\n|.', '\\1', text)

标签: r regex


【解决方案1】:

您应该注意,您针对带有文字 \n(反斜杠 + n)的字符串进行了测试,并且您使用了 PCRE 正则表达式风格(\w++ 包含所有格量词)并且您需要使用 perl=TRUE in使用此类正则表达式的基本 R 正则表达式函数。

由于您只想从特定字符串中获取文本到换行符,因此最好的模式是一组替代品,然后是一个否定字符类(匹配除\n 之外的任何字符)和一个换行符:

> text <- c("AND \n \n house notes: text text/text.\n \n text text \n text",
+           "AND \n \n notes: text text/text.\n \n text text \n text",
+           "AND \n \n house: text text/text.\n \n text text \n text")
> 
> pat = "(house( notes)?|notes):[^\n]*\n"
> regmatches(text, gregexpr(pat, text))
[[1]]
[1] "house notes: text text/text.\n"

[[2]]
[1] "notes: text text/text.\n"

[[3]]
[1] "house: text text/text.\n"

详情

  • (house( notes)?|notes) - 匹配 househouse notesnotes 的组
  • : - 冒号
  • [^\n]* - 一个否定字符类,匹配除换行符以外的任何字符
  • \n - 换行符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多