Regex to match a C-style multiline comment

前端 未结 7 2214
忘了有多久
忘了有多久 2020-11-22 10:04

I have a string for e.g.

String src = \"How are things today /* this is comment *\\*/ and is your code  /*\\* this is another comment */ working?\"
         


        
7条回答
  •  [愿得一人]
    2020-11-22 10:43

    Try using this regex (Single line comments only):

    String src ="How are things today /* this is comment */ and is your code /* this is another comment */ working?";
    String result=src.replaceAll("/\\*.*?\\*/","");//single line comments
    System.out.println(result);
    

    REGEX explained:

    Match the character "/" literally

    Match the character "*" literally

    "." Match any single character

    "*?" Between zero and unlimited times, as few times as possible, expanding as needed (lazy)

    Match the character "*" literally

    Match the character "/" literally

    Alternatively here is regex for single and multi-line comments by adding (?s):

    //note the added \n which wont work with previous regex
    String src ="How are things today /* this\n is comment */ and is your code /* this is another comment */ working?";
    String result=src.replaceAll("(?s)/\\*.*?\\*/","");
    System.out.println(result);
    

    Reference:

    • https://www.regular-expressions.info/examplesprogrammer.html

提交回复
热议问题