我有一系列的表达方式,例如:
"<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解析器可能更可靠.
如果这是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)
你可以用下面的办法与gregexpr和regmatches,如果你不知道比赛中字符串的数量.
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)