user576700
user576700

Reputation: 610

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

I have task where I have to open many files, search for //@public object pattern, and if it has no matches, remove all JavaScript comments inside that file that do not have //@public doc before it.

For example, there might be something similar to this:

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

and that remains as is. But every other JavaScript comment needs to be removed.

What would be regular expression for it, and how to achieve that?

Thank you in advance.

In the meanwhile, I came up to do following solution

    <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>

Which filters fileset including only those file that do not contain //@public object, but I dont have idea how to make regexp which will strip all comments except those which are preceeded by line //@public doc

Solved it this way:

<!-- 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>

Upvotes: 2

Views: 513

Answers (1)

Pulak Agrawal
Pulak Agrawal

Reputation: 2481

I would break it down in this way:

  1. Select files which contain the pattern.
  2. Run replace task on the specific regex.

Something like

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

I have not tested it , so you might need to tweak the regex a bit.

Upvotes: 2

Related Questions