R中用于花括号的递归正则表达式 [英] Recursive regex in R for curly braces
问题描述
我在以下模式中有一些文本字符串.
I have some text string in the following pattern.
x = "sdfwervd \calculus{fff}{\trt{sdfsdf} & \trt{sdfsdf} & \trt{sdfsdf} \\{} sdfsdf & sdfsdf & sefgse3 } aserdd wersdf sewtgdf"
-
我想使用正则表达式捕获字符串
\calculus{fff}
中的文本"fff"
,并将其替换为其他内容.
I want to use regex to capture the text
"fff"
in the string\calculus{fff}
and replace it with something else.
我还想在\calculus{.+}
之后的第一个{
和对应的右花括号}
之间捕获字符串.
Further I want to capture the string between the first {
after \calculus{.+}
and it's corresponding closing curly brace }
.
如何在R中使用正则表达式执行此操作?
How to do this with regex in R ?
以下内容捕获了直到最后一个花括号为止的所有内容.
The following captures everything till last curly brace.
gsub("(\\calculus\\{)(.+)(\\})", "", x)
推荐答案
对于第二个任务,您可以在基础R
中将递归方法与regmatches()
和gregexpr()
结合使用:
For the second task you can use a recursive approach in combination with regmatches()
and gregexpr()
in base R
:
x <- c("sdfwervd \\calculus{fff}{\\trt{sdfsdf} & \\trt{sdfsdf} & \\trt{sdfsdf} \\{} sdfsdf & sdfsdf & sefgse3 } aserdd wersdf sewtgdf")
pattern <- "\\{(?:[^{}]*|(?R))*\\}"
(result <- regmatches(x, gregexpr(pattern, x, perl = TRUE)))
这将产生找到的子匹配项的列表:
This yields a list of the found submatches:
[[1]]
[1] "{fff}"
[2] "{\\trt{sdfsdf} & \\trt{sdfsdf} & \\trt{sdfsdf} \\{} sdfsdf & sdfsdf & sefgse3 }"
See a demo for the expression on regex101.com.
这篇关于R中用于花括号的递归正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!