Add a new line symbol after "{" or ";" or "}" in java when using line builder

When using the stringbuilder class, I need to add "\ n" after each "{" or "}" or ";". And then you need to write the same thing in the file.

Output object stringbuilder ie

System.out.println(sb.toString());

is an

nav {  ul {    list-style: none;    margin: 0;    padding: 0;  }  li { display: inline-block; }  a {        display: block;    padding: 6px 12px;    text-decoration: none;  }

Please, help. Thanks

+4
source share
5 answers

Use a positive lookbehind as shown below.

string.replaceAll("(?<=[{;}])", "\n");

Explanation:

  • (?<=[{;}])A positive lookbehind states that a match must be preceded by {either }or or ;.

  • , look-behind, . , { } ;.

  • \n .

+7

:

System.out.println( sb.toString().replaceAll("([{};])", "$1\n") );

{ OR } ; : [{};] $1 ( ). $1, \n ( ), .

+5

String - {};,

String str = "nav {  ul {    list-style: none;    "
    + "margin: 0;    padding: 0;  }  li { "
    + "display: inline-block; }  a { display: block;"
    +"    padding: 6px 12px;    text-decoration: none;  }";
for (char ch : str.toCharArray()) {
    System.out.printf("%c", ch);
    if (ch == '{' || ch == '}' || ch == ';') {
        System.out.println();
    }
}

( )

nav {
  ul {
    list-style: none;
    margin: 0;
    padding: 0;
  }
  li {
 display: inline-block;
 }
  a {
 display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
+2

:

.

        char [] arraySb = sb.toCharArray();
        String result = "";

        for(char singleLetter : arraySb){
            if(singleLetter == '{' || singleLetter == '}' || singleLetter == ';'){
                result += (singleLetter + "\n");
            }else{
                result += singleLetter;
            }
        }
0
source

Try executing Java code:

String line = "nav {  ul {    list-style: none;    margin: 0;    padding: 0;  }  li { display: inline-block; }  a {        display: block;    padding: 6px 12px;    text-decoration: none;  }";
System.out.println(line.replaceAll("(?<=(\\{|\\}|;))", "\n"));
0
source

All Articles