Skip to content

Check if String starts with a number in Java example

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.

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.

This method returns true if the specified character is a digit.

Output

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,

Output

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.

About the author

Leave a Reply

Your email address will not be published.