【问题标题】:Matching LaTeX Commands and convert them to XML tags匹配 LaTeX 命令并将它们转换为 XML 标签
【发布时间】:2021-11-01 08:14:24
【问题描述】:

我正在尝试从 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' 这显然意味着它无法匹配许多嵌套模式。

有什么帮助吗?

【问题讨论】:

    标签: c# regex latex


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-17
      • 2022-01-20
      • 2015-02-09
      • 2022-11-14
      • 2012-09-10
      • 1970-01-01
      相关资源
      最近更新 更多