0

I need help with the pattern to distinguish between single line comments and URLs using a regex, both of them have // for example:

// this is a single line comment
var foo = "http://google.com";
var bar = 1; // This is another single line comment

I want to match comments only and ignore the URLs and other strings that are not comments.

Here is the regex I have tried:

/(\/\/.*)/g

I am trying to replace the single line comments in the production ready code.

Delimitry
  • 2,987
  • 4
  • 30
  • 39
Punith Raj
  • 2,164
  • 3
  • 27
  • 45

1 Answers1

1
(?=^\/\/).*

Use this. See demo.

http://regex101.com/r/pP3pN1/22

Edit:

Use this is comments can be in middle as well.

(?!^http:\/\/.*$)^.*?(\/\/.*$)

See demo

http://regex101.com/r/pP3pN1/29

vks
  • 67,027
  • 10
  • 91
  • 124
  • 2
    what if the comments present at the middle? – Avinash Raj Sep 03 '14 at 10:55
  • @AvinashRaj that isnt really mentioned in the question neither the regex tried by OP suggests so. – vks Sep 03 '14 at 10:56
  • consider providing a general solution. – Avinash Raj Sep 03 '14 at 10:58
  • @vks.. partially true. but consider this code statement.. ".success(function (data, status, headers, config) { //Comment goes here" where comment is present at end of line.. can you correct above answer considering this. – Punith Raj Sep 03 '14 at 17:02
  • @vks.. yes tested it too.. but it selected all the preceding char in the statement.. I am using this for removing the comments from production ready code. it should match all char to the end of line. but not all preceding charecters – Punith Raj Sep 03 '14 at 17:15
  • @vks.. I realy appriciate for all your help !!! but lookback not supported in javascript. can you help me with this in JS? – Punith Raj Sep 03 '14 at 17:26
  • @vks .. the matching information is correct. But the substitution part is removing the entire statement. http://regex101.com/r/mK9wZ7/2 – Punith Raj Sep 04 '14 at 05:23
  • tested for above, version 3 has broken for http:// pattern.... http://regex101.com/r/mK9wZ7/4 – Punith Raj Sep 04 '14 at 06:50
  • http://regex101.com/r/mK9wZ7/6 not working if http:// is not first char of line:)... guess this will be the last one :) – Punith Raj Sep 04 '14 at 07:41