pcregrep:如何只匹配第一次出现?

pcregrep: how to match only the first occurence?

我有很多格式如下的文件:

SIMPLE
{
    residualControl
    {
        p               1e-4;
        U               1e-4;
        "(k|omega|epsilon)" 1e-4;
    }
    nNonOrthogonalCorrectors 0;
    pRefCell        0;
    pRefValue       0;

}

potentialFlow
{
    nNonOrthogonalCorrectors 10;
}

relaxationFactors
{
    fields
    {
        p               0.3;
    }
    equations
    {
        U               0.7;
        "(k|omega|epsilon).*" 0.7;
    }
}

我想匹配文件夹 $FOAM_TUTORIALS/incompressible 中所有文件中的以下文本块:

    residualControl
    {
       // line 1
       // line 2
       // ...etc
    }

当我使用pcregrep时如下:

    pcregrep --color -r -M "residualControl.*\n.*\{(.*\n)*" $FOAM_TUTORIALS/incompressible/

它也匹配其他行(见下面的评论):

SIMPLE
{
    residualControl
    {
        p               1e-4;
        U               1e-4;
        "(k|omega|epsilon)" 1e-4;
    } // <<<<<<<<<<<<<<<<<<<<<<<<<<< I want it to stop match here. But it matches also the lines below
    nNonOrthogonalCorrectors 0;
    pRefCell        0;
    pRefValue       0;

}

potentialFlow
{
    nNonOrthogonalCorrectors 10;
}

relaxationFactors
{
    fields
    {
        p               0.3;
    }
    equations
    {
        U               0.7;
        "(k|omega|epsilon).*" 0.7;
    }
}

你能告诉我如何修改正则表达式以仅匹配第一个块吗?

您可以使用此正则表达式进行搜索:

pcregrep --color -r -M '^\h*residualControl\s*{[^}]*}' $FOAM_TUTORIALS/incompressible/

residualControl
{
    p               1e-4;
    U               1e-4;
    "(k|omega|epsilon)" 1e-4;
}

正则表达式详细信息:

  • ^\h*: 在行首匹配 0 个或多个水平空格
  • residualControl\s*:匹配字符串residualControl后跟0个或多个空格(包括换行符)
  • {: 比赛开始{
  • [^}]*:匹配0个或多个不是}
  • 的字符(包括换行符)
  • }:比赛结束}