Removing all Comments

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Gizmor
Forum Newbie
Posts: 1
Joined: Mon Feb 25, 2008 2:36 pm

Removing all Comments

Post by Gizmor »

Hi,

I'm trying to remove all comments from an javascript-file. So I need to remove all /* ... */ an // ...
That's not a big problem. My Problem is that it is possible that these things can also stand inside strings.

So let me give you some samples:

Code: Select all

xxxx //comment
should become xxxx

Code: Select all

xxxx /* comment
comment */
 
should become xxxx

Code: Select all

var = 'xxx //nocomment'; //comment
should become var = 'xxx //nocomment';

Code: Select all

var = 'xxx /* nocomment'; /*comment*/
should become var = 'xxx /* nocomment';

I started to create a regex for this:

Code: Select all

/(?<!')\/\/.*/
and

Code: Select all

/(?<!('|"))\/\*.+\*\//
but this only works if the comment begins right after the ' an not like shown in the samples.

I hope you understand what i'm trying to do and anyone can help me with this.
Thanks!
Post Reply