The first code doesn’t work because "seq"
(in quotes) is a String
which contains the text "seq", and has nothing to do with the variable seq
.
That is to say, "seq".matches("\\d")
is checking whether the String
(the text) "seq"
contains a number. But like this String
only has letters (s
, e
and q
), the return is false
.
If you want to check the contents of the variable seq
, remove the quotes and use the variable itself directly:
String seq ="7865";
boolean numeros = seq.matches("\\d"); // <-- repare que seq está sem as aspas
System.out.println("Possui números? " + numeros);
But the above code will still return false
, because the method matches
checks whether the String
integer matches regex. How regex is \\d
, it only checks if the String
contains one digit (exactly one, so the second code with "1".matches("\\d")
works).
Anyway, if you want to validate that the String
whole only has numbers from start to finish, use:
boolean numeros = seq.matches("^\\d+$");
Now we have the markers ^
and $
, which are respectively the beginning and end of the string, and the quantifier +
, which indicates "one or more occurrences". That is, regex checks whether the String
has only one or more digits from start to finish.
You could also place specific quantities if you like. Examples:
\\d{11}
: exactly 11 digits
\\d{4,11}
: not less than 4, not more than 11 digits
\\d{4,}
: at least 4 digits, with no upper limit
Adjust the values for whatever you need.
But as you said you want to validate CPF, regex is not the best solution. Regular expressions always work with text, and even digits are treated as mere characters, regardless of their numerical value. regex will only check if the string has only digits, but CPF validation also includes calculations to check the check digits, and that is much easier to do without regex. Though it has its usefulness, regex is not always the best solution.
really tested here and it worked that way. Thank you so much for the explanation.
– Marin
@Marin If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. And when I get 15 points, you can also vote in all the answers you found useful.
– hkotsubo