Using Regex to remove css comments

后端 未结 4 1022
执念已碎
执念已碎 2021-01-23 16:56

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 comm

相关标签:
4条回答
  • 2021-01-23 17:29

    Very late reply but thought it will be useful for some

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

    This will help removing css comments both singleline and multiline.
    
    0 讨论(0)
  • 2021-01-23 17:31

    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.

    0 讨论(0)
  • 2021-01-23 17:52

    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.

    0 讨论(0)
  • 2021-01-23 17:53

    Use the regex from the linked question like so:

    var rx = new Regex(@"(?<!"")\/\*.+?\*\/(?!"")");
    
    0 讨论(0)
提交回复
热议问题