【问题标题】:R capture everything from pattern until patternR 捕获从模式到模式的所有内容
【发布时间】:2013-03-12 12:31:55
【问题描述】:

我正在尝试在 BB</p> 两个模式之间提取一个子字符串:

require("stringr")
str = "<notes>\n  <p>AA:</p>\n   <p>BB: word, otherword</p>\n    <p>Number:</p>\n    <p>Level: 1</p>\n"
str_extract(str, "BB.*?:</p>")

提取的子串应该是“word, otherword”,但是我抓的太多了:

  [1] "BB: word, otherword</p>\n    <p>Number:</p>"

【问题讨论】:

  • .* 是贪婪的。它将一直捕获到最后一次出现 &lt;/p&gt;
  • @Arun 实际上,.* 是贪婪的,但 .*? 不是。我认为这是一个错位的冒号,但问题仍然没有完全解决。
  • 哎呀,看?,你是对的。

标签: regex r capture


【解决方案1】:

也许是这样的?

> gsub(".*BB: (.*?)</p>.*$", "\\1", str)
# [1] "word, otherword"

【讨论】:

  • gsub 适用于我的应用程序,然后我不需要 stringr 包。谢谢!
【解决方案2】:

这是 Perl 正则表达式的工作。即,lookahead 和lookbehind 引用。在stringr 中,您可以将正则表达式包装在perl 函数中,如下所示:

str_extract(str, perl("(?<=BB: ).*?(?=</p>)"))
[1] "word, otherword"

你也可以用 base 来做到这一点:

regmatches(str, regexpr(perl("(?<=BB: ).*?(?=</p>)"), str, perl=TRUE))
[1] "word, otherword"

【讨论】:

  • 谢谢,我觉得还是用base比较好
猜你喜欢
  • 2011-07-03
  • 2019-06-28
  • 2021-09-05
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
相关资源
最近更新 更多