Replace in empty line

Asked

Viewed 112 times

1

I have a variable with the following content:

10
20 30
40 50 60

70 80 90


100

There are spaces (can be 2 or more in a row) and line breaks (also several in the sequence), and I want to replace to stay this way:

10
20
30
40
50
60
70
80
90
100

Each value in a row, no empty lines and no spaces.

I tried for the conteudo = conteudo.replace(" ", "\n"); but the empty lines stay.

Have to replace everything at once or clear these empty lines after breaking all values ?

  • Variable of type String?

  • @Laerte this, String !

  • There you want to turn into another string only formatted the way you posted, right or want a list with the values?

  • In the same String, already "treated"

1 answer

4


To remove the empty lines you can use the method replaceAll with the regular expression \n+

String tratar = "10\n"
        + "20 30\n"
        + "40 50 60\n"
        + "\n"
        + "70 80 90\n"
        + "\n"
        + "\n"
        + "100";

String nova = tratar.replace(" ", "\n").replaceAll("\n+", "\n");

System.out.println(nova);

Functional Example: https://ideone.com/AQYWsK

  • 1

    Wouldn’t it be easier to use only one regex for both things ? With for example \s+|\n+.

  • 1

    Yes possible, only a correction in regex: \\s+|\n+

Browser other questions tagged

You are not signed in. Login or sign up in order to post.