This Java example shows how to check if the string starts with a number in Java using regular expression or the charAt
and isDigit
methods.
How to check if string starts with a number in Java?
1) Check using the charAt and isDigit methods
Use the charAt
method of the String class to get the first character of the String.
1 |
public char charAt(int index) |
This method returns character at the specified index of the string. You can then use the isDigit
static method of the Character class to check if the first character of the string is a number.
1 |
public static boolean isDigit(char ch) |
This method returns true if the specified character is a digit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.javacodeexamples.stringexamples; public class StringStartsWithNumberExample { public static void main(String[] args) { String[] strValues = { "Hello World", "123Hello World", "9 Carlton Avenue", "p1ssw0rd" }; for(String str : strValues){ char ch = str.charAt(0); if(Character.isDigit(ch)) System.out.println(str + " starts with a number"); else System.out.println(str + " does not start with a number"); } } } |
Output
1 2 3 4 |
Hello World does not start with a number 123Hello World starts with a number 9 Carlton Avenue starts with a number p1ssw0rd does not start with a number |
2) Check using the regular expression
You can check if the string starts with a number using the regular expression and the matches
method of the String class. We are going to use the “^[0-9].*$” pattern to do the same where,
1 2 3 4 |
^ - start of the string [0-9] - character between 0 to 9 .* - followed by any characters $ - end of the String |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.javacodeexamples.stringexamples; public class StringStartsWithNumberExample { public static void main(String[] args) { String[] strValues = { "Hello World", "123Hello World", "9 Carlton Avenue", "p1ssw0rd" }; for(String str : strValues){ if(str.matches("^[0-9].*$")) System.out.println(str + " starts with a number"); else System.out.println(str + " does not start with a number"); } } } |
Output
1 2 3 4 |
Hello World does not start with a number 123Hello World starts with a number 9 Carlton Avenue starts with a number p1ssw0rd does not start with a number |
You can also use the “^\\d.*$” pattern instead of the “^[0-9].*$” pattern where “\\d” means any digit.
This example is a part of the String in Java tutorial.
Please let me know your views in the comments section below.