我有一个形式的文本:
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溶液。
您可以使用
\\examples({([^{}]*?(?:(?1)[^{}]*?)*)\s*})
请参阅regex演示。
细节
\\examples
-一个\examples
字符串({([^{}]*?(?:(?1)[^{}]*?)*)\s*})
-第1组(由于正则表达式子例程(?1)
将递归此子模式,因此是必要的):
{
-一个{
字符([^{}]*?(?:(?1)[^{}]*?)*)
-第2组(您需要的值):
[^{}]*?
-零个或多个字符,{
且}
尽可能少(?:(?1)[^{}]*?)*
-整个第1组模式中出现零次或多次出现,其次是零个或多个字符,{
且字符}
数尽可能少\s*
-零个或多个空格(在结尾处修剪空格}
)}
-一个}
字符参见R演示:
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}"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句