为什么正则表达式匹配组的结尾与第二个匹配?

时间:2015-06-15 17:51:01

标签: regex

我对以下正则表达式的原因感到困惑:

CHANGES:(.|\n)*(\*\/)

匹配第二个评论结束(*/)而不是下一个区块中的第一个:

 /* ysqwwqdeqwd 
 Some general start comments and code description

 DESCRIPTION:

    Interface for c

 CHANGES:

    $Log: blala.h,v $
    Revision 1.7  2008/09/08 18:34:43  p
    Updated copyright year.
 */

#define startofcode yeah

/* General include files for Object Oriented C code.
 */
#include "oo.h"
#include "const.h"
#include "libmath.h"

在这里我们会得到这个:

CHANGES:
    ...

 */

#define startofcode yeah

/* General include files for Object Oriented C code.
 */

而不只是:

CHANGES:
        ...

     */

here is a live example.这里的背景是我试图从一堆不再需要的.h文件的顶部删除一堆旧的CVS样式的svn提交日志。

1 个答案:

答案 0 :(得分:2)

CHANGES:(.|\n)*?(\*\/)

              ^^

您需要non greedy正则表达式。请参阅演示。当您使用greedy正则表达式时,它将在*/的最后一个实例处停止。当您使用非贪婪时,它将在第一个实例处停止*/*是贪婪的,会消耗尽可能多的东西。

https://regex101.com/r/vH0sZ0/3