Remove all blank spaces at the beginning and end of a regular expression word

0

I need your help because I have a regular expression for all the blanks at the beginning and end of a word, but I have tried in several ways and I can not get the expected result, can you please guide me.

Word 1:     4. numero de identificación

Word 2: 3. nombre    

Regular Expression

String texto = texto.replaceAll("^\s{2,}|$\s|\s+(?=\s)", "")

Tests conducted:

Test No. 1a

String textoA = "3. nombre    ";

String resultadoA = textoA.trim(); **resultado:** '3. nombre 

Test No. 1b

String textoA = "3. nombre    ";

String resultadoA = textoA .replaceAll("^\s{2,}|$\s|\s+(?=\s)", "");

Expected result:

Word 1: 4. numero de identificación

Word 2: 3. nombre

    
asked by Gdaimon 27.12.2018 в 23:46
source

2 answers

1

You can use the following regular expression to remove 'blanks' (spaces, tabs, ...) at the beginning and end of a string:

mensaje.replaceAll("^\p{Zs}+|\p{Zs}+$", "");

It seems that trim does not work because the text in question must be using one of the other alternative unicode spaces

With respect to the regular expression, the difference with respect to \s is that \s would only deal with the ASCII spaces, while \p{Zs} also takes the unicode spaces into account.

Another option could be to use StringUtils.strip , as discussed in this entry in StackOverflow. It seems that it would work with the different unicode spaces.

    
answered by 02.01.2019 / 15:23
source
1

You may not be calling the trim function correctly, try it this way:

public class Task {

    public static void main(String[] args) {


        String source = "    4. numero de identificación    ";
        String result = source.trim();

        System.out.println(result);

    }

}

Documentation: trim function

    
answered by 28.12.2018 в 02:03