strip indent in groovy multiline strings

后端 未结 7 938
名媛妹妹
名媛妹妹 2020-12-08 13:49

Unfortunately stripIndent on a multiline string does not work. Side note: My IDE code style preferences allow only space indentation (tabs will be replaced by spaces). But i

7条回答
  •  孤城傲影
    2020-12-08 14:13

    I have a similar use-case because I'd like to format my SQL query in line. For example the nested query:

    String query = '''
        select ${CONTROL_ID} from ${TABLE_NAME} 
            where 
                location_id = ( 
                    select id from location where code = ${locationCode} 
                )  
    ''';
    

    Looks a lot better in Groovy than a Java version with "..."+ TABLE_NAME +"..." as I'm sure you can agree.

    This kind of string doesn't work with the .stripIndent() method. Instead I retained the new lines in query (above) for a purpose -- Note no "\" at the end of line.

    And thus

    String query = """
        select ${CONTROL_ID} from ${TABLE_NAME} 
            where 
                location_id = ( 
                    select id from location where code = '${locationCode}' 
                )  
    """.replaceAll( /\n\s*/, " " );
    
    println  "  Query= ${query};"; 
    

    Give a neatly formatted single line SQL query result:

      Query = select id from controls where  location_id = (  select id from location where code = '003');
    

    Which I find quite helpful and easier to read. I replace with a single space to make sure the SQL stays discrete. The important part is to use the newline(\n) as a de facto start-line or anchor. Fine for mixed TAB-s and SPACE-s.

    Of course it also works for the original question too.

提交回复
热议问题