Regex 如何在不替换的情况下进行全局搜索?

Regex 如何在不替换的情况下进行全局搜索?,regex,bash,perl,Regex,Bash,Perl,出于某种原因,这个正则表达式 perl -ne 'print "$1\n" if /\\includegraphics\[[^\]]*\]\{([^\}]*)/g' test.tex 当我给它时,它不会全局搜索 \centerline{\includegraphics[height=70mm]{FIGS/plotTangKurve3}\includegraphics[height=70mm]{FIGS/plotTangKurve2}\includegraphics[height=70mm]{

出于某种原因,这个正则表达式

perl -ne 'print "$1\n" if /\\includegraphics\[[^\]]*\]\{([^\}]*)/g' test.tex 
当我给它时,它不会全局搜索

\centerline{\includegraphics[height=70mm]{FIGS/plotTangKurve3}\includegraphics[height=70mm]{FIGS/plotTangKurve2}\includegraphics[height=70mm]{FIGS/plotTangKurve1}}
\centerline{\includegraphics[height=70mm]{FIGS/plotTangKurve3}\includegraphics[height=70mm]{FIGS/plotTangKurve2}\includegraphics[height=70mm]{FIGS/plotTangKurve1}}
它只输出数据

FIGS/plotTangKurve3
FIGS/plotTangKurve3
我希望得到的是

FIGS/plotTangKurve3
FIGS/plotTangKurve2
FIGS/plotTangKurve1
FIGS/plotTangKurve3
FIGS/plotTangKurve2
FIGS/plotTangKurve1
问题:


有人知道为什么会这样吗?

要搜索一些文本,最好使用带PCRE选项的grep:


\K用于重置匹配信息。

要搜索某些文本,最好使用带PCRE选项的grep:

\K用于重置匹配的信息。

您将希望在while而不是if中执行

g进行全局匹配,但这意味着每个后续匹配都返回一个新值。因为使用if,所以只对正则表达式求值一次,而从不尝试后续的潜在匹配。如果改用while,您将重新评估它,直到它失败

换言之:

perl -ne 'print "$1\n" while /\\includegraphics\[[^\]]*\]\{([^\}]*)/g' test.tex
这给了我您想要的输出。

您将希望在while而不是if中执行

g进行全局匹配,但这意味着每个后续匹配都返回一个新值。因为使用if,所以只对正则表达式求值一次,而从不尝试后续的潜在匹配。如果改用while,您将重新评估它,直到它失败

换言之:

perl -ne 'print "$1\n" while /\\includegraphics\[[^\]]*\]\{([^\}]*)/g' test.tex
这将为我提供所需的输出。

$1最多只引用一个匹配项。解决此问题的一种方法是捕获并打印每行上的所有匹配项:

perl -ne 'print "$_\n" for /\\includegraphics\[[^\]]*\]\{([^\}]*)/g'

$1仅指最多一场比赛。解决此问题的一种方法是捕获并打印每行上的所有匹配项:

perl -ne 'print "$_\n" for /\\includegraphics\[[^\]]*\]\{([^\}]*)/g'