Validating Strings as Alphanumeric Using Regex in Java
To validate alphanumeric characters using regular expressions, use ^[a-zA-Z0-9]+$
. This regular expression matches strings composed of one or more alphanumeric characters, such as "3DModel".
If you want to specify a fixed length of alphanumeric characters, use ^[a-zA-Z0-9]{n}$
. For example, to match exactly 6 characters, use ^[a-zA-Z0-9]{6}$
. Similarly, you can create flexible patterns by specifying minimum and maximum lengths. For instance, ^[a-zA-Z0-9]{12,20}$
is effective for matching strings between 12 and 20 characters.
Below is a summary of commonly used regular expression patterns. Feel free to use them as needed.
# | Match Condition | Regular Expression Pattern |
---|---|---|
1 | Contains only alphanumeric characters | ^[a-zA-Z0-9]+$ |
2 | Fixed length of n alphanumeric characters | ^[a-zA-Z0-9]{n}$ |
3 | At least n alphanumeric characters | ^[a-zA-Z0-9]{n,}$ |
4 | No more than m alphanumeric characters | ^[a-zA-Z0-9]{1,m}$ |
5 | Between n and m alphanumeric characters | ^[a-zA-Z0-9]{n,m}$ |
Source Code
Below is a Java function to validate if a given string consists only of alphanumeric characters. The function allows validation based on the following conditions:
- If the minimum length is omitted: Validates that the string is within the specified maximum length and consists only of alphanumeric characters.
- If the maximum length is omitted: Validates that the string meets the minimum length requirement and consists only of alphanumeric characters.
- If both minimum and maximum lengths are omitted: Validates that the string entirely consists of alphanumeric characters.
/**
* Checks whether a string consists only of alphanumeric characters.
*
* This function verifies if the string is composed within the specified
* range of length and consists only of alphanumeric characters.
*
* @param str The input string.
* @param minLength The minimum number of characters (treated as 1 if null).
* @param maxLength The maximum number of characters (treated as the string's length if null).
* @return true if the input string meets the conditions, otherwise false.
* @throws IllegalArgumentException Throws an exception if the minimum length is less than 1,
* or the maximum length is less than the minimum length.
*/
public static boolean isAlphanumeric(String str, Integer minLength, Integer maxLength) {
if (str == null) {
throw new IllegalArgumentException("Input string must not be null.");
}
int min = (minLength == null) ? 1 : minLength;
int max = (maxLength == null) ? str.length() : maxLength;
// Validate the arguments
if (min < 1) {
// Throw an exception if the minimum length is less than 1
throw new IllegalArgumentException("The minimum length must be an integer greater than or equal to 1.");
}
if (maxLength != null && max < min) {
// Throw an exception if the maximum length is less than the minimum length
throw new IllegalArgumentException("The maximum length must be greater than or equal to the minimum length.");
}
// Build the regex pattern
String regex = (maxLength == null)
? String.format("^[a-zA-Z0-9]{%d,}$", min) // When the maximum length is not specified
: String.format("^[a-zA-Z0-9]{%d,%d}$", min, max); // When the range is specified
// Validate the string using the regex pattern
return Pattern.matches(regex, str);
}
Test Cases
import java.util.regex.Pattern;
public class Main {
/**
* Checks whether a string consists only of alphanumeric characters.
*
* This function verifies if the string is composed within the specified
* range of length and consists only of alphanumeric characters.
*
* @param str The input string.
* @param minLength The minimum number of characters (treated as 1 if null).
* @param maxLength The maximum number of characters (treated as the string's length if null).
* @return true if the input string meets the conditions, otherwise false.
* @throws IllegalArgumentException Throws an exception if the minimum length is less than 1,
* or the maximum length is less than the minimum length.
*/
public static boolean isAlphanumeric(String str, Integer minLength, Integer maxLength) {
if (str == null) {
throw new IllegalArgumentException("Input string must not be null.");
}
int min = (minLength == null) ? 1 : minLength;
int max = (maxLength == null) ? str.length() : maxLength;
// Validate the arguments
if (min < 1) {
// Throw an exception if the minimum length is less than 1
throw new IllegalArgumentException("The minimum length must be an integer greater than or equal to 1.");
}
if (maxLength != null && max < min) {
// Throw an exception if the maximum length is less than the minimum length
throw new IllegalArgumentException("The maximum length must be greater than or equal to the minimum length.");
}
// Build the regex pattern
String regex = (maxLength == null)
? String.format("^[a-zA-Z0-9]{%d,}$", min) // When the maximum length is not specified
: String.format("^[a-zA-Z0-9]{%d,%d}$", min, max); // When the range is specified
// Validate the string using the regex pattern
return Pattern.matches(regex, str);
}
/**
* Main method for testing the functionality of the isAlphanumeric method.
*
* @param args Command-line arguments (not used)
*/
public static void main(String[] args) {
// Test Case 1: Valid input (meets the condition)
System.out.println("Test Case 1: " + isAlphanumeric("hello123", 3, 10)); // true
// Test Case 2: Does not meet the minimum length
System.out.println("Test Case 2: " + isAlphanumeric("hello123", 10, null)); // false
// Test Case 3: Contains non-alphanumeric characters
System.out.println("Test Case 3: " + isAlphanumeric("hello!123", 1, null)); // false
// Test Case 4: Exceeds the maximum length
System.out.println("Test Case 4: " + isAlphanumeric("abc", null, 2)); // false
// Test Case 5: Valid input (contains only alphanumeric characters)
System.out.println("Test Case 5: " + isAlphanumeric("ABC123", 1, 6)); // true
// Test Case 6: Empty string
System.out.println("Test Case 6: " + isAlphanumeric("", 1, null)); // false
// Test Case 7: Contains only alphanumeric characters within the specified range
System.out.println("Test Case 7: " + isAlphanumeric("test123", 4, 8)); // true
// Test Case 8: No maximum length specified, meets the condition
System.out.println("Test Case 8: " + isAlphanumeric("abcdef123", 5, null)); // true
// Test Case 9: Length matches the minimum length
System.out.println("Test Case 9: " + isAlphanumeric("abc", 3, 5)); // true
// Test Case 10: Length matches the maximum length
System.out.println("Test Case 10: " + isAlphanumeric("abcde", 1, 5)); // true
}
}