Reverse gsub

I have the html code I'm working with. I want to extract specific rows.

I want to extract this from line x using base R :coleman_l, SMOG4

Here is what I have:

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))

Error message:

> 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

NOTE : marked as a regular expression, but it is a specific R-regular expression.

+5
source share
3 answers

For these types of problems, I would use backlinks to extract the part I want.

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)"

If the brackets also need to be removed, add them to the part of the "plain text" that you link to match, but remember that they will need to escape:

gsub(".*a></code>\\((.+?)\\)<br.*", "\\1", x)
# [1] "coleman_l, SMOG4"
+8
source

FWIW, OP's original approach could work with a little customization.

> 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"
+7

This will work despite the ugliness.

x<-"<code>(hi)<a href=\"Read\">auto</a></code>(coleman_l, SMOG4)<br />Read</li>"

x2 <- gsub("^.+(\\(.+\\)).+\\((.+)\\).+$","\\2",x)
x2
[1] "coleman_l, SMOG4"
+5
source

All Articles