gpt4 book ai didi

正则表达式匹配 LaTeX 方程

转载 作者:行者123 更新时间:2023-12-04 11:26:58 27 4
gpt4 key购买 nike

我正在尝试将 TeXWorks 编辑器配置为使用与 TeXMaker 相同的语法着色。但是,TexWorks 使用正则表达式来指定应该着色的内容。不幸的是,它没有数学的默认设置。

我想匹配 $ 之间的所有内容和 $ ,\[之间的一切和 \] ,\(之间的一切和 \) ,$$之间的一切和 $$ .后者不是很有必要,因为它在 LaTeX 文档中很少使用。

它也可以是多个正则表达式来匹配所有情况。

当然\$被转义了,所以我不想匹配它,也不想匹配 \\[等等。

然后我也想匹配 \begin{equation} 之间的所有内容和 \end{equation} ,但这很简单。

“这是不可能的”是一个可能的答案。

最佳答案

试试这个 PCRE 正则表达式:

(?<!\\)    # negative look-behind to make sure start is not escaped 
(?: # start non-capture group for all possible match starts
# group 1, match dollar signs only
# single or double dollar sign enforced by look-arounds
((?<!\$)\${1,2}(?!\$))|
# group 2, match escaped parenthesis
(\\\()|
# group 3, match escaped bracket
(\\\[)|
# group 4, match begin equation
(\\begin\{equation\})
)
# if group 1 was start
(?(1)
# non greedy match everything in between
# group 1 matches do not support recursion
(.*?)(?<!\\)
# match ending double or single dollar signs
(?<!\$)\1(?!\$)|
# else
(?:
# greedily and recursively match everything in between
# groups 2, 3 and 4 support recursion
(.*(?R)?.*)(?<!\\)
(?:
# if group 2 was start, escaped parenthesis is end
(?(2)\\\)|
# if group 3 was start, escaped bracket is end
(?(3)\\\]|
# else group 4 was start, match end equation
\\end\{equation\}
)
))))

查看此正则表达式的实际效果: https://regex101.com/r/wP2aV6/25

由于此正则表达式使用递归,它将正确处理嵌套的数学表达式。

这仅适用于 PCRE 兼容的正则表达式引擎。它需要正则表达式引擎的一些高级特性,如负向后视、条件表达式和递归,这些特性在所有正则表达式引擎中都不存在。

除非你需要一些非常简单的东西,否则我建议不要使用这个正则表达式,而是使用适当的 LaTeX 解析器。

关于正则表达式匹配 LaTeX 方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14182879/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com