使用R中的正则表达式在某些符号之间提取文本

Jav*_*ier 10 regex r

我有一系列的表达方式,例如:

"<i>the text I need to extract</i></b></a></div>"
Run Code Online (Sandbox Code Playgroud)

我需要在<i></i>"符号" 之间提取文本.这样,结果应该是:

"the text I need to extract"
Run Code Online (Sandbox Code Playgroud)

目前我在R中使用gsub来手动删除所有非文本的符号.但是,我想使用正则表达式来完成这项工作.有谁知道正则表达式提取之间<i></i>

谢谢.

G. *_*eck 18

如果<i>...</i>示例中只有一个,则匹配所有内容<i>和来自</i>forward的所有内容,并用空字符串替换它们:

x <- "<i>the text I need to extract</i></b></a></div>"
gsub(".*<i>|</i>.*", "", x)
Run Code Online (Sandbox Code Playgroud)

赠送:

[1] "the text I need to extract"
Run Code Online (Sandbox Code Playgroud)

如果同一个字符串中可能出现多次,请尝试:

library(gsubfn)
strapplyc(x, "<i>(.*?)</i>", simplify = c)
Run Code Online (Sandbox Code Playgroud)

在这个例子中给出相同的内容.


Tyl*_*ker 10

这种方法使用的是我维护qdapRegex的软件包,它不是正则表达式,但可能对您或未来的搜索者有用.该功能rm_between允许用户在左右边界之间提取文本,并可选择包含它们.这种方法很简单,因为您不必考虑特定的正则表达式,只需要确切的左右边界:

library(qdapRegex)

x <- "<i>the text I need to extract</i></b></a></div>"

rm_between(x, "<i>", "</i>", extract=TRUE)

## [[1]]
## [1] "the text I need to extract"
Run Code Online (Sandbox Code Playgroud)

我想指出,为这项工作使用html解析器可能更可靠.


Ric*_*ven 5

如果这是html(它看起来像是),你应该使用html解析器.包XML可以做到这一点

library(XML)
x <- "<i>the text I need to extract</i></b></a></div>"
xmlValue(getNodeSet(htmlParse(x), "//i")[[1]])
# [1] "the text I need to extract"
Run Code Online (Sandbox Code Playgroud)

在整个html文档中,您可以使用

doc <- htmlParse(x)
sapply(getNodeSet(doc, "//i"), xmlValue)
Run Code Online (Sandbox Code Playgroud)


Sve*_*ein 5

你可以用下面的办法与gregexprregmatches,如果你不知道比赛中字符串的数量.

vec <- c("<i>the text I need to extract</i></b></a></div>",
         "abc <i>another text</i> def <i>and another text</i> ghi")

regmatches(vec, gregexpr("(?<=<i>).*?(?=</i>)", vec, perl = TRUE))
# [[1]]
# [1] "the text I need to extract"
# 
# [[2]]
# [1] "another text"     "and another text"
Run Code Online (Sandbox Code Playgroud)