我正在尝试从tex文件中提取所有的latex命令,然后将命令转换为xml标记。为此,我必须使用C#。
我现在可以使用这个regex匹配命令。
\\(?<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库来使用这个regex \\(?<command>(?:[^a-zA-Z]|[a-zA-Z]+[*=']?))(?<param>\[.+\])*(\{(?<content>(?:[^{}]*|(?R))+)\})进行递归匹配,但是我得到了这个异常PCRE.PcreMatchException: 'match limit exceeded',这显然意味着它不能匹配许多嵌套模式。
有什么帮助吗?
发布于 2021-09-05 08:45:05
举个例子,您可以尝试
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#演示。\\(\w+)\{([^{}]*)}模式匹配
\\ -反斜杠(\w+) -第1组:任何一个或多个单词字符(字母、数字、下划线)\{ -a { char([^{}]*) -第2组:除{和}以外的任何零或多个字符} -a } char.注意到:如果在\\\w+\{和}部件之间有其他的{或},这是行不通的。对这种格式的任意字符串使用专用解析器将是一种解决方案。
https://stackoverflow.com/questions/69037266
复制相似问题