【问题标题】:regex - get content inside matching braces正则表达式 - 获取匹配大括号内的内容
【发布时间】:2020-12-05 12:24:41
【问题描述】:

我有一个文本格式:

text <- "\\examples{afunction(x = list()){\nx<-3\n}y<-2 server <- function(input, output, session) {\n  output$res_bttn1 <- renderPrint({input$bttn1})\n}\n}"

我想获取\\examples{}的内容(末尾没有\n),即

"afunction(x = list()){\nx<-3\n}y<-2 server <- function(input, output, session) {\n  output$res_bttn1 <- renderPrint({input$bttn1})\n}"

问题是\\examples{} 中还有其他大括号。因此,我认为我必须找到一个正则表达式来检测哪个} 关闭\\examples{(但我愿意接受其他关于如何获得相同结果的建议)。

我该怎么做?首选 R 基溶液。

【问题讨论】:

  • 这行得通吗? sub('examples\\{(.*)\n\\}', '\\1', text) 匹配到最后一个 '\n' ?
  • 这对这个例子来说很好,但我不确定在最后的}之前总会有一个\n

标签: r regex


【解决方案1】:

你可以使用

\\examples({([^{}]*?(?:(?1)[^{}]*?)*)\s*})

请参阅regex demo

详情

  • \\examples - \examples 字符串
  • ({([^{}]*?(?:(?1)[^{}]*?)*)\s*}) - 第 1 组(这是必要的,因为正则表达式子例程 (?1) 将递归此子模式):
    • { - 一个 { 字符
    • ([^{}]*?(?:(?1)[^{}]*?)*) - 第 2 组(您需要的值):
      • [^{}]*? - 除{} 之外的零个或多个字符尽可能少
      • (?:(?1)[^{}]*?)* - 整个第 1 组模式出现零次或多次,后跟零个或多个字符,而不是 {} 尽可能少
    • \s* - 零个或多个空格(修剪尾随 } 之前的空格)
    • } - 一个 } 字符

R demo

text <- "\\examples{afunction(x = list()){\nx<-3\n}y<-2 server <- function(input, output, session) {\n  output$res_bttn1 <- renderPrint({input$bttn1})\n}\n}"
pattern = "\\\\examples({([^{}]*?(?:(?1)[^{}]*?)*)\\s*})"
unlist(regmatches(text, regexec(pattern, text, perl=TRUE)))[3]
# => [1] "afunction(x = list()){\nx<-3\n}y<-2 server <- function(input, output, session) {\n  output$res_bttn1 <- renderPrint({input$bttn1})\n}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 2011-09-06
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多