You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则表达式为独立$$包裹的LaTeX公式添加反引号

问题描述

我使用的平台仅支持用$$和$$包裹的LaTeX公式,必须给独立的公式块添加反引号才能被识别。需要把原内容中独立的开头$$替换为\$$,结尾$$替换为$$``。

原内容示例

If the object moves at a constant speed over a distance of $2L$ in a straight line within time $2t$, then the time elapsed for the object is:

$$
\tau_1 = 2t \sqrt{1 - \left(\frac{L}{ct}\right)^2}
$$

期望效果

If the object moves at a constant speed over a distance of $2L$ in a straight line within time $2t$, then the time elapsed for the object is:

`$$
\tau_1 = 2t \sqrt{1 - \left(\frac{L}{ct}\right)^2}
$$`

已尝试但无效的正则表达式

匹配单个$的公式:
(?<!\$)\$([^\$]+)\$(?!\$)
匹配两个$的公式:
(?<!\$)\$\$([^\$]+)\$\$(?!\$)
匹配单个$:
(?<!\$)\$(?!\$)
解决方案

正则匹配与替换方案

针对独立的多行公式块($$开头结尾,中间包含换行),可以用以下正则进行全局替换:

匹配正则

(?<!`)^\$\$(.*?)\$\$$

需开启多行模式和非贪婪模式,部分工具需额外开启DOTALL模式让.匹配换行符。

替换为

`$$
$1
$$`

正则逻辑解释

  1. **(?<!)**:确保匹配的$$`前没有反引号,避免重复处理已添加反引号的公式块。
  2. ^\$\$:在多行模式下匹配行首的$$。
  3. (.*?):非贪婪匹配$$和结尾$$之间的所有内容,若工具不支持DOTALL,可替换为[\s\S]*?来匹配所有空白/非空白字符。
  4. \$\$$:在多行模式下匹配行尾的$$。

这个正则也能兼容单行的$$...$$公式块,无需额外调整。

内容的提问来源于stack exchange,提问作者user26615363

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 02:45:06