To check if string contains number in Java, you can either loop over each character of string and check if it’s a digit or you can use regex.
public static boolean checkIfStringContainsDigit(String passCode){ for (int i = 0; i < passCode.length(); i++) { if(Character.isDigit(passCode.charAt(i))) { return true; } } return false; }
Introduction
There are situations when we need to find if our string contains numbers, lowercase letter, uppercase letter, special character etc. One such example is password. In order to define its strength, we create a protocol on the length of password as well as the characters it contains. To determine that we need to check the string if it contains required characters.
In this article we are going to learn about the regex methods provided by Java. We will also define a method based on loop to check character by character.
Code Example 1: Check digit in string
In this code, we will write a java method which can detect if the string contains a digit.
public static boolean checkIfStringContainsDigit(String passCode){ for (int i = 0; i < passCode.length(); i++) { if(Character.isDigit(passCode.charAt(i))) { return true; } } return false; }
Here we have created a method checkIfStringContainsDigit
which accepts a string parameter passCode
. It then loops over the length of the string and check each character if that is a digit using isDigit
method from Character
class. Our method returns true as soon as it finds the first digit or return false after the loop ends.
Code Example 2: Using regex
Now we will check how java regex could be used to look into the string for different kinds of characters.
public int multiChecker(String pass){ int passwordStrength = 0; int conditionsFulfilled = 0; if (Pattern.compile("[0-9]").matcher(pass).find()) { passwordStrength = passwordStrength + 10; conditionsFulfilled += 1; } if (Pattern.compile("[a-z]").matcher(pass).find()) { passwordStrength = passwordStrength + 5; conditionsFulfilled += 1; } if (Pattern.compile("[A-Z]").matcher(pass).find()) { passwordStrength = passwordStrength + 15; conditionsFulfilled += 1; } return passwordStrength + (conditionsFulfilled * 5); }
In the above code we have created a method multiChecker
which accepts a string parameter pass
. The purpose of this code is to check if pass
contains digits, lowercase and uppercase letters. Accordingly we are determining the strength of password as well as the number of conditions fulfilled.
For this we are using Pattern
and matcher
functionality. It compiles the provided regex and then match it with the string.