java check if string only contains numbers using regex

Java
[Edit]
+
0
-
0

Java check if string only contains numbers using regex

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String[] args) { String numbers = "1234"; String text = "ABC"; String regex = "^[0-9]+$"; // regex to check if string contains only digits Pattern pattern = Pattern.compile(regex); // compiles the regex // find match between given string and pattern Matcher matcherNumbers = pattern.matcher(numbers); Matcher matcherText = pattern.matcher(text); // return true if the string matched the regex Boolean numbersMatches = matcherNumbers.matches(); Boolean textMatches = matcherText.matches(); System.out.println(numbersMatches); // true System.out.println(textMatches); // false } }