You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写正则表达式匹配代码中的/* ... */注释块?

提取C风格/* ... */注释块的正则表达式

要提取代码中所有独立的/* ... */注释块,你可以使用以下正则表达式:

/\*[^*]*\*+(?:[^/*][^*]*\*+)*/

正则表达式拆解

  • /\*:精准匹配注释的起始符号/*
  • [^*]*:匹配任意数量的非*字符
  • \*+:匹配一个或多个连续的*
  • (?:[^/*][^*]*\*+)*:非捕获分组,处理注释内部可能出现的*但不是结束标记*/的情况,避免提前终止匹配
  • /:匹配注释的结束符号/

示例用法(Python)

针对你给出的代码行:

%6 = nn.conv2d(%5, meta[relay.Constant][0] /* ty=Tensor[(32, 3, 6, 6), int8] */, strides=[2, 2], padding=[0, 0, 0, 0], channels=32, kernel_size=[6, 6], out_dtype="int32") /* ty=Tensor[(1, 32, 320, 320), int32] */;

用Python的re模块提取注释:

import re

code_line = '%6 = nn.conv2d(%5, meta[relay.Constant][0] /* ty=Tensor[(32, 3, 6, 6), int8] */, strides=[2, 2], padding=[0, 0, 0, 0], channels=32, kernel_size=[6, 6], out_dtype="int32") /* ty=Tensor[(1, 32, 320, 320), int32] */;'
pattern = r'/\*[^*]*\*+(?:[^/*][^*]*\*+)*/'
matches = re.findall(pattern, code_line)

print(matches)
# 输出: ['/* ty=Tensor[(32, 3, 6, 6), int8] */', '/* ty=Tensor[(1, 32, 320, 320), int32] */']

内容的提问来源于stack exchange,提问作者irasin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 05:20:28