在变量中查找LaTeX?

时间:2017-01-04 15:31:36

标签: regex perl

在下面的脚本中,我想将$$包裹在乳胶部分周围。这是在\begin{center}之前和\end{center}之后,但它可以是任何\begin{} / \end{}对。

底部的原始文字位于$f

问题

任何人都可以看到为什么我的脚本插入了太多$$

我的剧本

my @lines = split "\n", $f;
$f = "";
my $btype = "";
my $flag = 1;
for my $line (@lines) {
   $flag = $1 if $line =~ /\\begin\{(.*?)\}/;
   if ($flag ne 0) {
       $line = "\$\$\n$line";
       $flag = 0;
   }
   $f .= "$line\n";
}

我的输出

$$
begin:text
# Question intro text for dec04opg10

$$
\begin{center}
$$
\begin{tabular}{l|ccc}
& SURF & VOL & MW \\ \hline
SURF &1 & 0.995 & 0.949 \\
VOL &  0.995 & 1 & 0.952 \\
MW & 0.949 & 0.952 & 1 \\ \hline
\end{tabular}
\end{center}
end:text

begin:multiple_choice

原始文字

begin:text
# Question intro text for dec04opg10

\begin{center}
\begin{tabular}{l|ccc}
& SURF & VOL & MW \\ \hline
SURF &1 & 0.995 & 0.949 \\
VOL &  0.995 & 1 & 0.952 \\
MW & 0.949 & 0.952 & 1 \\ \hline
\end{tabular}
\end{center}
end:text

begin:multiple_choice

所需的输出

begin:text
# Question intro text for dec04opg10

$$
\begin{center}
\begin{tabular}{l|ccc}
& SURF & VOL & MW \\ \hline
SURF &1 & 0.995 & 0.949 \\
VOL &  0.995 & 1 & 0.952 \\
MW & 0.949 & 0.952 & 1 \\ \hline
\end{tabular}
\end{center}
$$
end:text

begin:multiple_choice

1 个答案:

答案 0 :(得分:2)

您需要先关闭$flag,然后还需要跟踪$btype。您已经拥有变量,但您没有使用它。由于您只需要最外面的对,因此如果您还没有begin,则只需要捕获$btype

my @lines = split "\n", $f;
$f = "";
my $btype;
my $flag = 0;
for my $line (@lines) {

    # put in the beginning
    if ( not $btype and $line =~ /\\begin\{(.*?)\}/ ) {
        $flag  = 1;
        $btype = $1;
    }
    if ($flag) {
        $line = "\$\$\n$line";
        $flag = 0;
    }

    # now use $btype to find the end ...

    $f .= "$line\n";
}

此输出

begin:text
# Question intro text for dec04opg10

$$
\begin{center}
\begin{tabular}{l|ccc}
& SURF & VOL & MW \\ \hline
SURF &1 & 0.995 & 0.949 \\
VOL &  0.995 & 1 & 0.952 \\
MW & 0.949 & 0.952 & 1 \\ \hline
\end{tabular}
\end{center}
end:text

begin:multiple_choice