2

How can I remove comments from CSS using Regex.Replace()?

Note - I'm not able to use the regex mentioned here in C# - Regular expression to remove CSS comments.

Community
  • 1
  • 1
NLV
  • 21,141
  • 40
  • 118
  • 183
  • 4
    Why are you not able to use it? – Daniel Hilgarth Mar 11 '11 at 11:18
  • I suspect it's because PHP uses Perl-regexes. – Anonymous Coward Mar 11 '11 at 11:25
  • Now that's an exemplary attitude, providing the link for duplicate closing by your own. Oh, by the way, your question should be a comment on the answer at that question. – Bobby Mar 11 '11 at 11:26
  • possible duplicate of [Regular expression to remove CSS comments](http://stackoverflow.com/questions/3984380/regular-expression-to-remove-css-comments) – Bobby Mar 11 '11 at 11:26
  • @Daniel I dont understand regular expressions quite well and the regex given in that link was having some escape characters issue in C#. – NLV Mar 11 '11 at 13:30
  • @Bobby The question was clearly asked for PHP and even I tried that too before posting the question. So I don't think that in any way it is a duplicate. Thanks for appreciating my attitude, though. – NLV Mar 11 '11 at 13:31
  • @NLV See my answer. That regex should work, I tested it with the same line as in the linked question. – Daniel Hilgarth Mar 11 '11 at 13:41
  • @Bobby - remember that the .Net and PHP regular expression engines are completely different implementations. You can get different behavior from them both for the exact same regular expression. This is also true of other regular expression engines (e.g. JavaScript regular expressions which can vary depending on the client's browser!). – Doctor Jones Mar 11 '11 at 13:45
  • @NLV: I apologize, I completely missed the PHP tag. Though I was able to get the posted solution working by simply stripping the `/` from it. @DoctaJonez: I know that they're completely different engines (as said, I missed the PHP tag), but under normal conditions (and with the standard set) they *should* deliver the same result. At least that's my opinion. But as said, I apologize for my sloppy vote. – Bobby Mar 11 '11 at 14:02

4 Answers4

9

That would be normally enough (assuming cssLines is a string containing all lines of your CSS file):

 Regex.Replace(cssLines, @"/\*.+?\*/", string.Empty, RegexOptions.Singleline)

Please note that the Singleline option will allow to match multi-line comments.

Maxim Gueivandov
  • 2,370
  • 1
  • 20
  • 33
2

Use the regex from the linked question like so:

var rx = new Regex(@"(?<!"")\/\*.+?\*\/(?!"")");
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

I wonder if the following version of Maxim's solution would be faster.

"/\*[^*]*.*?\*/"

As the discussion shows this will also eliminate comments within string literals.

vbence
  • 20,084
  • 9
  • 69
  • 118
0

Very late reply but thought it will be useful for some

"(?:/*(.|[\r\n])?/)|(?:(?([^)])//.)"

This will help removing css comments both singleline and multiline.