Java String Handling RegEx

Check if String starts with a number in Java example

This Java example shows how to check if String starts with a number in Java. Example also shows how to check if String starts with a number using regular expression or charAt and isDigit methods.

How to check if String starts with a number in Java?

There are couple of ways in which you can check if String starts with a number in Java.

1) Check if String starts with a number using charAt and isDigit methods

Use charAt method of String class to get the first character of the String.

This method returns char at the specified index. You can then use isDigit static method of 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 if String starts with a number using regular expression

You can check if String starts with a number using regular expression and matches method of String class. We are going to use “^[0-9].*$” pattern to do the same where,

Output

You can also use “^\\d.*$” pattern instead of “^[0-9].*$” where \\d denotes any digit.

Please let us know your views in the comments section below.

 

Tags
Join 1000+ fellow learners! Enter your email address below: