如何用正则表达式替换特定的JavaScript注释

How can I replace specific JavaScript comments with a regular expression?

本文关键字:JavaScript 注释 何用 正则表达式 替换      更新时间:2023-09-26

我的任务是打开许多文件,搜索//@public object模式,如果它没有匹配项,则删除该文件中之前没有//@public doc的所有JavaScript注释。

例如,可能有类似的东西:

//@public doc
    /**
     * @function
     * checks for specific conditions
     * specific variables
     */

但其他所有JavaScript注释都需要删除。

什么是正则表达式,以及如何实现?

提前谢谢。

与此同时,我想出了以下解决方案

    <fileset id="jsmvcdoc.fileset" dir="${doctempfolder}" includes="**/*.js">
        <not>
         <contains text="//@public object" casesensitive="no"/>
        </not>
    </fileset>
   <!-- JS Comments -->
   <replaceregexp match="(?!doc. +)/'*.+?'*/" replace="" flags="gs" byline="false">
        <fileset refid="jsmvcdoc.fileset"/>
   </replaceregexp>

它过滤文件集,只包括那些不包含//@public对象的文件,但我不知道如何制作regexp,它将删除所有注释,除了前面有//@public-doc 行的注释

通过这种方式解决:

<!-- strip out js comments not preceeded by //@public doc -->
  <replaceregexp match="(?&lt;!//@public doc'x0D'x0A    )/'*.+?'*/" replace="" flags="gs" byline="false">
        <fileset refid="jsmvcdoc.fileset"/>
  </replaceregexp>

我会用这种方式分解它:

  1. 选择包含图案的文件
  2. 在特定regex上运行replace任务

类似的东西

<replaceregexp byline="true">
  <regexp pattern="/'*['d'D]*?'*/"/>
    <substitution expression=""/>
       <fileset dir="${JSfiles.path}" includes="**/*.js">
          <contains text="//@public object" casesensitive="no"/>
       </fileset>
</replaceregexp>

我还没有测试过它,所以您可能需要稍微调整一下regex。