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

批量将单美元符号LaTeX公式转换为\( \)格式的正则方案需求

Solution Using Perl Regular Expressions

Since you need to batch convert single-dollar math expressions ($formula$) to LaTeX inline math (\(formula\)) while preserving double-dollar block math ($$formula$$), here's a reliable terminal command using Perl (preinstalled on most Linux/macOS systems):

The Command

perl -pi.bak -e 's/(?<!\$)\$([^\$]+)\$(?!\$)/\\($1\\)/g' *.txt

Breakdown of How It Works

  • perl: Invokes the Perl interpreter, which handles advanced regex lookarounds better than basic tools like sed.
  • -pi.bak:
    • -p: Processes each line of input files and prints the modified output.
    • -i.bak: Edits files in place and creates a backup of each original file with a .bak extension (safe for testing—you can revert if needed!).
  • -e '...': Runs the specified regex substitution logic.
  • Regex details:
    • (?<!\$): Negative lookbehind—ensures the $ we're matching isn't preceded by another $ (avoids touching $$ block math).
    • \$: Matches a single literal $.
    • ([^\$]+): Captures the content inside the single $ (all characters except $, which is standard for inline math).
    • \$(?!\$): Matches the closing $, with a negative lookahead to ensure it's not followed by another $.
    • \\($1\\): Replaces the matched pattern with \( + the captured formula + \).

Usage Tips

  1. Target Files: Replace *.txt with your actual file pattern (e.g., *.md for Markdown files, *.tex for LaTeX files).
  2. Backup Cleanup: After verifying the conversion is correct, delete the .bak backup files with rm *.bak.
  3. Windows Users: Use WSL (Windows Subsystem for Linux) or install Perl via Strawberry Perl to run this command.
  4. Edge Cases: This regex assumes your single-dollar expressions don't contain literal $ characters inside them (standard for inline math). If you have exceptions, let me know and we can adjust the logic!

Example Test

Running the command on your sample input:

Before: This is $a+b_{k}+c$ sentence. Another test $s_\text{hi}+3$. $x=y$ there. $$y=z$$ why? $$z=z$$ This could be ($3^2$, $x_1$).

Produces exactly the desired output:

After: This is (a+b_{k}+c) sentence. Another test (s_\text{hi}+3). (x=y) there. $$y=z$$ why? $$z=z$$ This could be ((3^2), (x_1)).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:44:32