Exclude Specific String Within Regex/gsub

Viewed 137

I am able to remove everything between "<>" and "</>" using:

gsub("(<[^>]*>)","",abc)

I do not work with regex and can't figure out how to ignore a specific string.

My goal is to make a function where a user can supply values to ignore (i.e., ""), and then remove all values between "<>" or "</>" besides the ignored values.

character_vector <- c("<br>Hello</br>", "I want to keep this <important text>")

character_vector <- gsub("(<[^>]*>)","",character_vector)

Current Output:

[1] "Hello"                "I want to keep this "

Ideal Output:

[1] "Hello"                "I want to keep this <important text>"
1 Answers

You can use

character_vector <- c("<br>Hello</br>", "I want to keep this <important text> and <string?>")
exclude <- c("important text", "string?")
regex.escape <- function(string) {
  gsub("([][{}()+*^$|\\\\?.])", "\\\\\\1", string)
}
gsub(paste0("<(?!(?:", paste(regex.escape(exclude), collapse="|"), ")>)[^>]*>"), "", character_vector, perl=TRUE)
## => [1] "Hello"                                             
##    [2] "I want to keep this <important text> and <string?>"

See the R demo and the regex demo. The <(?!(?:important text|string\?)>)[^>]*> regex matches

  • < - a < char
  • (?!(?:important text|string\?)>) - a negative lookahead that fails the match if there is important text or string? followed with a > char immediately to the right of the current location
  • [^>]* - zero or more chars other than >
  • > - a > char.

The regex.escape function is necessary to escape any special char (], [, {, }, (, ), +, *, ^, $, |, \, ?, .) that comes in the exclude character vector items.

Related