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.

9
  • 4
    Why are you not able to use it? Commented Mar 11, 2011 at 11:18
  • I suspect it's because PHP uses Perl-regexes. Commented Mar 11, 2011 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. Commented Mar 11, 2011 at 11:26
  • possible duplicate of Regular expression to remove CSS comments Commented Mar 11, 2011 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#. Commented Mar 11, 2011 at 13:30

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Use the regex from the linked question like so:

var rx = new Regex(@"(?<!"")\/\*.+?\*\/(?!"")");

Comments

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.

4 Comments

it would not match if the comment itself contains the * character.
But it also doesn't work correctly ;-) It will detect comments inside strings. See the linked question for an example.
@Daniel: given that requirement, the proposed regexp in the linked comment will also wrongly match " before /* not a comment */ after". It's probably getting too complicated to handle all possible cases with regexps alone.
@Maxim: Indeed, you are right. I only checked the sample provided in the original question...
0

Very late reply but thought it will be useful for some

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

This will help removing css comments both singleline and multiline.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.