簡體   English   中英

排除 Regex/gsub 中的特定字符串

[英]Exclude Specific String Within Regex/gsub

我可以使用以下方法刪除“<>”和“</>”之間的所有內容:

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

我不使用正則表達式,也不知道如何忽略特定的字符串。

我的目標是制作一個 function,用戶可以在其中提供要忽略的值(即“”),然后刪除“<>”或“</>”之間的所有值,除了忽略的值。

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

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

當前 Output:

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

理想 Output:

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

您可以使用

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

請參閱R 演示正則表達式演示 <(??(:?important text|string\?)>)[^>]*>正則表達式匹配

  • < - 一個<字符
  • (??(:?important text|string\?)>) - 如果有important textstring? 緊跟在當前位置右側的>字符
  • [^>]* - 除>之外的零個或多個字符
  • > - 一個>字符。

regex.escape function 是轉義exclude字符向量項中的任何特殊字符 ( ][{}()+*^$|\?. ) 所必需的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM