我有一个 LaTeX 文档,看起来像这样:
Now, we go onto the following theorem:
\theorem{$\sqrt{2}$ is irrational.}{Blah blah blah...}
\remark{This proof is often attributed to Hippasus of Metapontum.}
We can prove a more general result:
\theorem{For $n$ a non-square integer, $\sqrt{n}$ is irrational.}{Blah blah blah...}
我想匹配所有看起来像
\theoremnoname{Something 1}{Something 2}
的东西,特别是,将 Something 1
和 Something 2
部分作为匹配的不同部分。
零件中存在未知数量的
{
和 }
,并试图让它们匹配时会出现困难。
我尝试过正则表达式
\theorem\{([^{}]+)\}(\{([^{}]*(\{[^{}]*\}[^{}]*)*)\})
(即使部分变得贪婪),但它没有返回任何匹配项。
如果您可以假设模式
}{
没有出现在第一组内,则正则表达式 \\theorem\{(.*)\}\{(.*)\}
应该可以工作。
我认为你的正则表达式前缀
\theorem\{([^{}]+)\}...
是错误的,这确实不会匹配任何内容,因为 \t
尝试匹配选项卡(所以使用 \\
代替)。但即使在那之后,您的正则表达式也只会到达第一个开头 {
,因为 [^{}]
仅匹配与 {
和 }
不同的字符,并且无法将找到的开头 {
与结尾 }
匹配。
我可以简单地使用 grep 并将这些部分放入两个文件中,如下所示:
cat your-doc.tex | grep -oE '\\theorem\{.*\}\{' | cut -c10- | rev | cut -c3- | rev > first.txt
cat your-doc.tex | grep -oE '\\theorem\{.*\}' | grep -oE '\}\{.*' | cut -c3- | rev | cut -c2- | rev > second.txt
这将为您提供示例文本的以下内容:
> cat first.txt
$\sqrt{2}$ is irrational.
For $n$ a non-square integer, $\sqrt{n}$ is irrational.
> cat second.txt
Blah blah blah...
Blah blah blah...