如何将多行注释与正则表达式匹配

问题描述 投票:0回答:5


我想将多行注释与正则表达式匹配。评论类型为:

/*
    This is a comment.
*/

我尝试这个代码:

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

问题图像是here
谢谢。

regex comments match multiline
5个回答
1
投票

根据您使用的正则表达式引擎,在匹配多个行字符串时应用不同的规则。

假设您使用 PCRE(在 PHP 中),此模式不匹配,因为默认情况下 PCRE 中的

.
不匹配换行符。也使用 this 模式 来匹配换行符:

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

您还可以使用原始模式并指定

/s
(单行)模式,但在这种情况下,前导和尾随换行符也将被捕获。


0
投票

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

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

0
投票

这个正则表达式应该找到所有评论:

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

0
投票

此正则表达式匹配所有多行注释,例如多行上的

/* ... */
,即使它们中包含
*
/

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

0
投票

用于单行和多行注释的 REGEXP (JS/C/C#)

在 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 */
在正则表达式前面加上额外的
 *
也很有用,这将选择注释之前的任何水平空白:
 *\/\*[\s\S\n]*?\*\/|\/\/.*$

will_select_this_area_as_well_together_with // the content of a deeply nested comment

当您必须对评论进行一些外部工作(例如翻译它们)时,这会很方便。通过复制空格,当您将注释粘贴回代码中时,您可以确保它们会滑回到原来的位置(按列)。

也就是说,为了避免错误并使该前缀更清晰,也应该可以将其写为

[[:space:]]*
,如下所示:

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

但是 VS Code/Codium 似乎还不支持这种语法,所以我坚持使用

 *
形式。

如果您在 https://regex101.com/ 上进行测试,请确保使用位于表达式末尾的硬编码“/”后面的开关设置“g”和“m”标志。

© www.soinside.com 2019 - 2024. All rights reserved.