Delete two or more blank spaces regular expression

2

I need your help because I have a regular expression to delete two or more blank spaces, but I have tried in several ways and I can not get the expected result, you can guide me please.

Case No. 1

String texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto = texto.replaceAll("\s+"," ");

Case No. 2

String texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto = texto.replaceAll("\s"," ");

Case No. 3

String texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto = texto.replaceAll(" +"," ");

Case No. 4

String texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto = texto.replaceAll("\s+"," ").trim();

Case No. 5

String texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto = texto.replaceAll("\s+"," ").replaceAll("^\s*","").replaceAll("\s*$","");

Case No. 6

String texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto = texto.replace("  "," ");

Expected result

String texto = "95716 B VO 21513836 269 60 S 50.40 3024.00 SI DCBO040818BLA";
    
asked by Gdaimon 18.08.2018 в 20:04
source

2 answers

5

try this:

String texto = " Esto  es una     prueba    ";
        texto=texto.trim();
        texto=texto.replaceAll("\s{2,}", " ");
        System.out.println(texto);

The "trim" function will remove the blank spaces that exist at the beginning and end of your chain.

And this line of code:

texto=texto.replaceAll("\s{2,}", " ");

It is interpreted like this, it replaces 2 or more blank spaces for a single space.

Greetings.

    
answered by 18.08.2018 / 20:27
source
0

Friend I hope and this will serve you :).

First Option.

var texto = "  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
texto_2 = texto.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
console.log(texto_2);

Second Option:

var string="  95716 B VO  21513836                        269     60 S          50.40          3024.00          SI          DCBO040818BLA";
                   
string3= string.trim().replace(/\s\s+/g, ' ');
                   
 console.log(string3);
    
answered by 18.08.2018 в 20:36