Notepad++正则表达式:将LaTeX章节转换为Markdown格式
TeX标题转Markdown标题的正则优化与批量处理方法
一、解决正则保留大括号的问题
你的正则之所以会保留大括号,是因为捕获组把{}也包含进去了。调整捕获组范围,只抓取大括号内的标题内容即可:
- 处理
\chapter{xxx}:
查找:\\chapter\{(.*?)\}
替换:# $1 - 处理
\section{xxx}:
查找:\\section\{(.*?)\}
替换:## $1 - 处理
\subsection{xxx}:
查找:\\subsection\{(.*?)\}
替换:### $1
注意:如果标题内容里包含嵌套大括号,非贪婪匹配
.*?可能失效,这种情况可以用更精准的正则\\chapter\{([^{}]+)\}(仅匹配不含大括号的标题内容)。
二、更高效的批量转换方法
如果有大量文件需要处理,手动逐个替换效率太低,可以用Python脚本批量处理:
import os import re # 定义标题转换规则 title_patterns = [ (re.compile(r'\\chapter\{(.*?)\}'), r'# \1'), (re.compile(r'\\section\{(.*?)\}'), r'## \1'), (re.compile(r'\\subsection\{(.*?)\}'), r'### \1'), # 可继续添加subsubsection等层级规则 ] def convert_tex_to_md(tex_file_path): # 读取TeX文件内容 with open(tex_file_path, 'r', encoding='utf-8') as f: content = f.read() # 依次应用替换规则 for pattern, replacement in title_patterns: content = pattern.sub(replacement, content) # 生成Markdown文件路径并保存 md_file_path = os.path.splitext(tex_file_path)[0] + '.md' with open(md_file_path, 'w', encoding='utf-8') as f: f.write(content) print(f"已转换:{tex_file_path} -> {md_file_path}") # 遍历指定目录下的所有TeX文件 tex_dir = './tex_files' # 替换为你的TeX文件所在目录 for root, dirs, files in os.walk(tex_dir): for file in files: if file.endswith('.tex'): convert_tex_to_md(os.path.join(root, file))
运行前将tex_dir替换为你的TeX文件目录,脚本会自动遍历所有.tex文件,转换后生成同名.md文件。
内容的提问来源于stack exchange,提问作者John Stone
相关产品推荐
相关产品推荐

