我有一些html代码。我想提取某些字符串。
我希望使用基R:coleman_l, SMOG4从字符串x首选项中提取这一信息。
以下是我所拥有的:
x <- "<code>(hi)<a href=\"Read\">auto</a></code>(coleman_l, SMOG4)<br />Read</li>"
#remove the string (this works)
gsub("a></code>(.+?)<br", "a></code><br", x)
#> gsub("a></code>(.+?)<br", "a></code><br", x)
#[1] "<code>(hi)<a href=\"Read\">auto</a></code><br />Read</li>"
#attempt to extract that information (doesn't work)
re <- "(?<=a></code>().*?(?=)<br)"
regmatches(x, gregexpr(re, x, perl=TRUE))错误消息:
> regmatches(x, gregexpr(re, x, perl=TRUE))
Error in gregexpr(re, x, perl = TRUE) :
invalid regular expression '(?<=a></code>().*?(?=)<br)'
In addition: Warning message:
In gregexpr(re, x, perl = TRUE) : PCRE pattern compilation error
'lookbehind assertion is not fixed length'
at ')'
enter code here注释:标记为regex,但这是R特定的regex。
发布于 2013-02-08 04:27:03
对于这些类型的问题,我会使用反向引用来提取我想要的部分。
x <-
"<code>(hi)<a href=\"Read\">auto</a></code>(coleman_l, SMOG4)<br />Read</li>"
gsub(".*a></code>(.+?)<br.*", "\\1", x)
# [1] "(coleman_l, SMOG4)"如果还应该删除括号,则将其添加到您正在绑定以匹配的“纯文本”部分,但请记住,它们需要转义:
gsub(".*a></code>\\((.+?)\\)<br.*", "\\1", x)
# [1] "coleman_l, SMOG4"发布于 2013-02-08 04:37:15
FWIW,OP最初的方法可以在很小的调整下起作用。
> x
[1] "<code>(hi)<a href=\"Read\">auto</a></code>(coleman_l, SMOG4)<br />Read</li>"
> re <- "(?<=a></code>\\().*?(?=\\)<br)"
> regmatches(x, gregexpr(re, x, perl=TRUE))
[[1]]
[1] "coleman_l, SMOG4"与其他建议的解决方案相比,这样做的好处是,如果存在多个匹配的可能性,那么所有的匹配都会出现。
> x <- '<code>(hi)<a href=\"Read\">auto</a></code>(coleman_l, SMOG4)<br />Read</li><code>(hi)<a href=\"Read\">auto</a></code>(coleman_l_2, SMOG4_2)<br />Read</li>'
> regmatches(x, gregexpr(re, x, perl=TRUE))
[[1]]
[1] "coleman_l, SMOG4" "coleman_l_2, SMOG4_2"发布于 2013-02-08 04:23:36
尽管很丑,但这会奏效的。
x<-"<code>(hi)<a href=\"Read\">auto</a></code>(coleman_l, SMOG4)<br />Read</li>"
x2 <- gsub("^.+(\\(.+\\)).+\\((.+)\\).+$","\\2",x)
x2
[1] "coleman_l, SMOG4"https://stackoverflow.com/questions/14765418
复制相似问题