regex 如何使用正则表达式匹配多行注解

dldeef67  于 9个月前  发布在  其他
关注(0)|答案(5)|浏览(105)

我想用正则表达式匹配多行注解。注解类型为:

/*
    This is a comment.
*/

我试试这个代码:

\/\*(.*?)\*\/

问题图像是

dz6r00yl

dz6r00yl1#

根据您使用的正则表达式引擎,在匹配多行字符串时应用不同的规则。
假设您正在使用PCRE(在PHP中),这个模式不匹配,因为默认情况下PCRE中的.不匹配换行符。也可以使用this pattern来匹配新行:

\/\*\s?(.*)\s?\*\/

您也可以use your original pattern和指定/s(单行)模式,但在这种情况下,前导和尾部换行符也将被捕获。

de90aj5v

de90aj5v2#

问题解决了!
我使用这个代码:

{
      'begin': '\\/\\*'
      'end': '\\*\\/'
      'name': 'comment.block.documention.mylanguage'
},
drnojrws

drnojrws3#

regex应找到所有评论:

\/\*\n((.*?)\n)+\*\/
4nkexdtk

4nkexdtk4#

这个正则表达式匹配所有多行注解,比如多行上的/* ... */,即使它们包含*/

\/\*(([^\*]|\*(?!\/))*)\*\/
4ioopgfo

4ioopgfo5#

REGEXP FOR SINGLE & MULTI-LINE COMMENTS(JS / C / C# / JAVA /etc.)

在VS Codium和https://regex101.com上测试

\/\*[\s\S\n]*?\*\/|\/\/.*$

这将正确匹配:

// single line comments

  /**
   * multi
   * line
   * comments
   * // including nested inline comments 
   * and without tripping on URL slashes (https://www.example.com)
   */

  /* single line comments written using multi-line delimiters */

  // /* single line comments written using MLDs and within a regular single line comment */

在regexp前面加上两个额外的*(一个在开头,一个在|),它还将选择单行和多行注解之前的所有水平空白:

*\/\*[\s\S\n]*?\*\/| *\/\/.*$

will_select_this_area_as_well_together_with // the content of a deeply nested comment

当你必须对注解做一些外部工作时,这会很方便。翻译)。通过复制空格,当你将注解粘贴回代码中时,你可以确保它们会滑回它们的原始位置(按列)。
也就是说,为了避免错误并使这些额外的部分更加清晰,也可以使用[[:space:]]*重写它,如下所示:

[[:space:]]*\/\*[\s\S\n]*?\*\/|[[:space:]]*\/\/.*$

然而,不幸的是,VS Code/Codium似乎还不支持这种语法,所以我坚持使用*形式。
希望能帮上忙!

注意:如果你在https://regex101.com/上测试,请确保使用位于表达式末尾“硬编码”/之后的开关设置gm标志。

相关问题