Activity Forums Salesforce® Discussions How to remove single and multi-line comments from a string in Salesforce apex?

  • shradha jain

    Member
    August 23, 2018 at 1:21 pm

    Hello Madhulika,
    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);

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

    //note the added \n which won't 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);

    Thanks.

  • shariq

    Member
    September 17, 2018 at 10:09 pm

    Hi,

    I think you need this -

    string str = 'this is test for newline \n this is actual newline.';
    system.debug(str.replace('\n',''));

    or

    string str = 'this is test for newline \r this is actual newline.';
    system.debug(str.replace('\r',''));

    Hope this helps.

  • Parul

    Member
    September 18, 2018 at 8:32 pm

    May be use this to remove:

    .replace(///.*?/?*.+?(?=n|r|$)|/*[sS]*?//[sS]*?*//g, ”)

     

    Thanks

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos