Regular expression to remove comment

后端 未结 5 2015
轮回少年
轮回少年 2021-02-07 14:49

I am trying to write a regular expression which finds all the comments in text. For example all between /* */. Example:

/* Hello */

5条回答
  •  故里飘歌
    2021-02-07 14:51

    I encountered this problem several years ago and wrote an entire article about it.

    If you don't have access to non-greedy matching (not all regex libraries support non-greedy) then you should use this regex:

    /\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/
    

    If you do have access to non-greedy matching then you can use:

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

    Also, keep in mind that regular expressions are just a heuristic for this problem. Regular expressions don't support cases in which something appears to be a comment to the regular expression but actually isn't:

    someString = "An example comment: /* example */";
    
    // The comment around this code has been commented out.
    // /*
    some_code();
    // */
    

提交回复
热议问题