Regex仅在级别1匹配另一个命令中的latex命令

vuktfyat  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(144)

有没有一种方法可以通过regexp匹配LaTeX命令(我主要使用perl进行替换),并用花括号将其括起来,另一方面,删除它们?
LaTeX命令可以是具有结构的文本的任何部分:它以反斜杠\开头,后跟命令名,可选地后跟括号,可选地后跟任意数量的花括号,其中可以有任何其他乳胶命令:

\com1[options]{ something possibly with \othercommand{ that } can also have arbitrary number of curly braces }

字符串
最后,我只想对所有第一层的命令(在另一个命令中)这样做。但我只能对外部命令这样做:

(?<=[^{])(\\(?:com1)(?:\[[^[]]*\])?(\{((?>[^{}]|(?2))*)\})*)


似乎可以很好地匹配任何零电平,然后简单地{$1}实现效果,例如:

\com1[opts]{ some \qtyrange{100}{200}{\celsius} and }{something else \gls{abc} $1=1$ not \colortext{\red}{\underline{text}}}


{\com1[opts]{ some \qtyrange{100}{200}{\celsius} and }{something else \gls{abc} $1=1$ not \colortext{\red}{\underline{text}}}}


然后回到:

\{(\\(?:com1)(?:\[[^[]]*\])?(\{((?>[^{}]|(?2))*)\})*)\}


替换为$1完成了这项工作。然而,当命令在另一个命令中时,平衡括号就变得难以捉摸了。基本上,我想

\rpl{text}{ some\com1[opts]{ some \qtyrange{100}{200}{\celsius} and }{something else \gls{abc} $1=1$ not \colortext{\red}{\underline{text}}} but this is already braced {\qtyrange{100}{200}{\celsius}}}


应该导致

\rpl{text}{ some {\com1[opts]{ some \qtyrange{100}{200}{\celsius} and }{something else \gls{abc} $1=1$ not \colortext{\red}{\underline{text}}}} but this is already braced {\qtyrange{100}{200}{\celsius}}}


也可以从最后一个例子中删除大括号,得到:

\rpl{text}{ some \com1[opts]{ some \qtyrange{100}{200}{\celsius} and }{something else \gls{abc} $1=1$ not \colortext{\red}{\underline{text}}} but this is already braced \qtyrange{100}{200}{\celsius}}


我玩过lookbehind,但由于我不能在其中使用量词,我不知道如何处理这个问题。

sgtfey8w

sgtfey8w1#

这个怎么样?(https://regex101.com/r/oBT25u/latest

(?<prefix>{[^\\}]++)(?<first_lvl_command>\\\w+(?:\[[^]]++]?({(?:[^{}]+|(?3))*+}))({(?:[^{}]+|(?3))*+})?)(?<closing_bracket>})

字符串
prefix group捕获所有内容,直到第一个嵌套命令。第一级命令捕获可选[...]和两次{...},可能使用递归嵌套括号。
无法编辑您的文章,因为它影响不到6个字符,但您在主命令的结尾缺少一个关闭}

相关问题