匹配 LaTeX 命令并将它们转换为 XML 标签

Matching LaTeX Commands and convert them to XML tags

我正在尝试从 tex 文件中提取所有 latex 命令,然后将命令转换为 xml 标签。我必须为此使用 C#。

我目前可以使用此正则表达式匹配命令

\(?<command>(?:[^a-zA-Z]|[a-zA-Z]+[*=']?))(?<param>\[.+\])*(?<content>\{.+?}{1,2})

目前可以匹配大多数命令,如 \command{foobar}\command[param]{foobar}\command[param]{foobar}{foobar},并将这些匹配替换为 <command attr1="param">content</command>,但我在匹配嵌套时遇到问题命令

例如

\firstcommand{\secondcommand{nestedcontent} outercontent} 应替换为 <firstcommand><secondcommand>nestedcontent</secondcommand> outercontent</firstcommand> 但我无法将此模式与我的正则表达式匹配

我最后的尝试是尝试使用 PCRE.NET 库来使用这个正则表达式 \(?<command>(?:[^a-zA-Z]|[a-zA-Z]+[*=']?))(?<param>\[.+\])*(\{(?<content>(?:[^{}]*|(?R))+)\}) 进行递归匹配,但是我得到了这个异常 PCRE.PcreMatchException: 'match limit exceeded' 这显然意味着它不能匹配很多嵌套模式。

有什么帮助吗?

你展示的例子,你可以试试

var text = @"\firstcommand{\secondcommand{nestedcontent} outercontent}";
var pattern = @"\(\w+)\{([^{}]*)}";
var prev = string.Empty;
do {
    prev = text;
    text = Regex.Replace(text, pattern, "<></>");
} while (prev != text);
Console.WriteLine(text);

它基本上是匹配和替换最里面的 word{...} 子串。 参见C# demo\(\w+)\{([^{}]*)} 模式匹配

  • \ - 反斜杠
  • (\w+) - 第 1 组:任何一个或多个单词字符(字母、数字、下划线)
  • \{ - 一个 { 字符
  • ([^{}]*) - 第 2 组:除 {}
  • 之外的任何零个或多个字符
  • } - 一个 } 字符。

注意:如果您在 \\w+\{} 之间有其他 {},这将不起作用部分。对这种格式的任意字符串使用专用解析器将是一种解决方案。