Why does this method return me the wrong amount of matches?

1
public int obtenerNumOraciones(String texto) {

    Pattern patron = Pattern.compile("[a-z]*");
    Matcher match = patron.matcher(texto);
    int cant = 0;
    while(match.find()){
        cant++;
    }

    return cant;
}

If I put text = hello, this method returns me 2, since I have to return a 1, I do not understand why it returns 2

    
asked by Christian H 07.10.2018 в 07:35
source

1 answer

1
  

[a-z] * - > Zero or more occurrences of a letter.

The matcher starts processing the string , finds a letter and starts making the first match .

When the letters are finished, what is left to continue processing is just the empty string.

But the problem is that your expression makes match with the empty string, so mark it as a new match .

The simplest solution could be (depending on what you are looking for) using + instead of * ; so the empty string is no longer a valid expression.

You can see a practical demonstration here: link

    
answered by 07.10.2018 / 11:03
source