Raw Strings in Java - for regex in particular. Multiline strings

前端 未结 12 1237
青春惊慌失措
青春惊慌失措 2020-12-01 02:13

Is there any way to use raw strings in Java (without escape sequences)?

(I\'m writing a fair amount of regex code and raw strings would make my code immensely more r

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 02:39

    Note : As of today, not available. Probably I'll edit this answer again whenever the feature release.

    There is an ongoing proposal to introduce Raw Strings in Java. They actually much useful in the cases of regex.

    Example 1: A regular expression string that was coded as

      System.out.println("this".matches("\\w\\w\\w\\w"));
    

    may be alternately coded as

    System.out.println("this".matches(`\w\w\w\w`));
    

    since backslashes are not interpreted as having special meaning.

    Example2 : A multi lines String literal with foreign language appends.

    A multiple line string that was coded as 
        String html = "\n" +
                    "    \n" +
                    "         

    Hello World.

    \n" + " \n" + "\n";

    may be alternately coded as

     String html = `
                           
                               

    Hello World.

    `;

    which avoids the need for intermediate quotes, concatenation and explicit newlines.

    Hopefully we can expect the release soon.

提交回复
热议问题