【问题标题】:Regex for old type of comment旧类型评论的正则表达式
【发布时间】:2012-08-18 23:50:02
【问题描述】:

我有这种cmets(几个例子):

  1. //========================================================================
    // some text some text some text some text some text some text some text 
    
  2. //========================================================================
    // some text some text some text some text some text some text some text some text
    // some text some text
    // (..)
    

我想用这种风格的评论替换它:

/*****************************************************************************\

Description:

    some text some text
    some text some text some text

\*****************************************************************************/

所以我需要正则表达式。我设法制作了这个正则表达式:

//=+\r//(.+)+

它匹配组中的注释,但只有一行(示例 1)。如何使其与多行 cmets 一起工作(如示例 2)?

感谢您的帮助

【问题讨论】:

标签: regex sed grep


【解决方案1】:

使用 sed:

sed -n '
  \_^//==*_!p;
  \_^//==*_{
    s_//_/*_; s_=_\*_g; s_\*$_\*\\_;
    h; p; i\
Desctiption:
    : l; n; \_//[^=]_{s_//_\t_;p;};t l;
    x;s_^/_\\_;s_\\$_/_;p;x;p;
  }
  ' input_file

评论版本:

sed -n '
  # just print non comment lines
  \_^//==*_!p;
  # for old-style block comments:
  \_^//==*_{
    # generate header line
    s_//_/*_; s_=_\*_g; s_\*$_\*\\_;
    # remember header, add description
    h; p; i\
Desctiption:
    # while comment continues, replace // with tab
    : l; n; \_//[^=]_{s_//_\t_;p;};t l;
    # modify the header as footer and print
    x;s_^/_\\_;s_\\$_/_;p
    # also print the non-comment line
    x;p;
  }
  ' input_file

【讨论】:

    【解决方案2】:

    这个正则表达式匹配整个评论

    (\/\/=+)(\s*\/\/ .+?$)+
    

    【讨论】:

    • 嗯,这对我不起作用。我正在这个网站上查看:gskinner.com/RegExr
    • 正确,必须替换正斜杠,谢谢! (ps 我只能访问 Rubular.com)
    【解决方案3】:

    一个简短的 perl 脚本,可以满足您的需要,在 cmets 中进行了解释:

    #!/usr/bin/perl -p
    
    $ast = '*' x 75;                  # Number of asterisks.
    if (m{//=+}) {                    # Beginning of a comment.
        $inside = 1;
        s{.*}{/$ast\\\nDescription:};
        next;
    }
    if ($inside) {
        unless (m{^//}) {             # End of a comment.
            undef $inside;
            print '\\', $ast, "/\n" ;
        }
        s{^//}{};                     # Remove the comment sign for internal lines.
    }
    

    【讨论】:

    • 是的描述是一个附加词。感谢您的回答!
    【解决方案4】:

    如果仍然需要正则表达式,不知道是否有更好的解决方案,这是我想出的:

    (?<=\/{2}\s)[\w()\.\s]+
    

    应该得到所有感兴趣的文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 2017-01-10
      相关资源
      最近更新 更多