1

我输入了类似以下示例的输入,并且只需要替换所有\input{.*}命令,这些命令前面没有%一行。

输入是 LaTeX 代码,其中%开始注释。这意味着%当前行之后的所有内容都不应被解释为实际代码,而实际上只是一个注释。(即使它看起来像代码)

示例输入:

this is \input{REAL.tex} real content    % \input{COMMENT.tex}
foo \input{REAL.tex} bar
\input{REAL.tex}
%\input{COMMENT.tex}
\input{REAL.tex} % comment

我当前的代码:

$r = "/^(?P<prefix>(?!.*%).*)\\\\input[{\s]+(?P<filename>.*?)[\s}](?P<suffix>.*)$/m";
$data = preg_replace($r, "REPLACED", $data);
echo $data . PHP_EOL;

当前示例输出:

this is \input{REAL.tex} real content    % \input{COMMENT.tex}
foo REPLACED bar
REPLACED
%\input{COMMENT.tex}
\input{REAL.tex}                         % comment

预期的示例输出:

this is REPLACED real content            % \input{COMMENT.tex}
foo REPLACED bar
REPLACED
%\input{COMMENT.tex}
REPLACED                                 % comment

问题:不幸的是,由于前瞻断言,由于中间\inputs的注释,我的正则表达式完全忽略了第一行和最后一行中的。%(?!.*%)

Question: Do you see a way to achieve the desired output via regular expressions? The \input{REAL.tex} on the first and last line should be replaced as well.

4

2 回答 2

2

You need a lookbehind that checks if there was a % before:

/(?<=%).*?\\\\input\{.+?\}/mis

Lookbehind syntax is (?<=(your regex)) for a negative lookbehind it is (?<!(your regex))

Integrated in your code this would look like

$data = 'this is \input{REAL.tex} real content % just a \input{COMMENT.tex}
foo \input{REAL.tex} bar
\input{REAL.tex}
%\input{COMMENT.tex}
\input{REAL.tex} % comment';

$r = "/(?<!%)([^%]*)\\\\input\{.+?\}/";
$data = preg_replace($r, '$1REPLACED', $data);

echo $newData . PHP_EOL;

Output is

this is REPLACED real content % just a \input{COMMENT.tex}
foo \input{REAL.tex} bar
REPLACED
%\input{COMMENT.tex}
REPLACED % comment
于 2013-11-07T10:42:33.980 回答
1

I just realized that i don't need to use lookaround here it all!

Code:

$r = "/^(?P<prefix>[^%]*?)\\\\input\\{(?P<filename>[^}]*)\\}(?P<suffix>.*)$/m";
$data = preg_replace($r, "\\1REPLACED\\3", $data);
echo $data . PHP_EOL;

Output:

this is REPLACED real content % just a \input{COMMENT.tex}
foo REPLACED bar
REPLACED
%\input{COMMENT.tex}
REPLACED % comment
于 2013-11-07T10:56:40.310 回答