标记后接收文字

问题描述

这提供了h1标签内的文本

library(rvest)
df1 <- data.frame(id = c(1,2),text = c("<h1> Title </h1> keep me here <h1>not </h1> or <h2> else</h2>","also not here <h1> but</h1> here also")
rawHTML <- paste(df1$text[1],collapse="\n")
rawHTML %>% read_html() %>% html_nodes("h1") %>% html_text()

在带有文本标题标签h1之后,应该向命令添加什么以接收什么?

示例输出: 让我在这里

解决方法

由于text是字符串,因此可以使用regex提取所需的数据。

stringr::str_extract(df1$text,'(?<=Title </h1>\\s).*(?=\\s<h1>)')
#[1] "keep me here" NA    

您也可以使用str_match,而不必进行简单的正则表达式和后瞻。

stringr::str_match(df1$text,'Title </h1>\\s(.*)\\s<h1>')[,2]
,

base R中,我们可以使用regmatches/gregexpr

with(df1,trimws(sapply(regmatches(text,gregexpr("(?<=Title </h1> )[^<]+",text,perl = TRUE)),`[`,1)))
#[1] "keep me here" NA