Skip to main content

Unifying Multi-Format Mathmatical Formula Delimiters via Regular Expressions

·109 words·1 min
Che
Author
Che
Just An Ordinary Person
Table of Contents

When editing Markdown, especially in scenarios involving page rendering, mathematical formulas often require specific escaped delimiters. Below are common delimiters and their corresponding regular expressions for efficient batch matching:

  1. Inline Formulas
  • \(...\):
(?<!\\)\\\((.*?)(?<!\\)\\\)
  • \\(...\\):
(?<!\\)\\\\\((.*?)(?<!\\)\\\\\)
  • $...$:
(?<!\$)\$(?!\$)(.*?)(?<!\$)\$(?!\$)
  1. Block Formulas
  • \[...\]:
(?<!\\)\\\[\n(.*?)\n(?<!\\)\\\]
  • \\[...\\]:
(?<!\\)\\\\\[\n(.*?)\n(?<!\\)\\\\\]
  • $$...$$:
(?<!\$)\$\$(?!\$)\n(.*?)\n(?<!\$)\$\$(?!\$)
  • \begin{equation}...\end{equation}:
(?<!\\)\\begin{equation}\n(.*?)\n(?<!\\)\\end{equation}

These patterns use negative lookbehinds ((?<!\\), (?<!\$)) and negative lookaheads ((?!\\\$, (?!\$) to avoid conflicts between delimiters (e.g., $...$ vs. $$...$$). For block formulas, line breaks (\n) are included but can be removed if unnecessary.

Replacement Rules
#

After matching, replacements can be performed using the following logic:

  • \(...\):
\\\($1\\\)
  • \\(...\\):
\\\\($1\\\\)
  • $...$:
$$$1$$
  • \[...\]:
\\[\n$1\n\\]
  • \\[...\\]:
\\\\[\n$1\n\\\\]
  • $$...$$:
$$$$\n$1\n$$$$
  • \begin{equation}...\end{equation}:
\begin{equation}\n$1\n\end{equation}