In this java regex tutorial, we will learn to test whether the length of input text is between some minimum and maximum limit.
All Programming languages provide an efficient way to check the length of text. However, using regular expressions to check text length can be helpful in some situations, particularly when the length is only one of the multiple rules determining whether the subject text fits the desired pattern.
1. Regex for Max and Min Characters
For example, following regular expression ensures that text is between 1 and 10 characters long, and additionally limits the text to the uppercase letters A–Z. You can modify the regular expression to allow any minimum or maximum text length or allow characters other than A–Z.
Regex : ^[A-Z]{1,10}$
2. Demo
List<String> names = List.of("LOKESH", "JAVACRAZY", "LOKESHGUPTAINDIA", "LOKESH123");
String regex = "^[A-Z]{1,10}$";
Pattern pattern = Pattern.compile(regex);
for (String name : names) {
Matcher matcher = pattern.matcher(name);
System.out.println(matcher.matches());
}
The program output:
true
true
false
false
I will advise playing with the above simple regular expression to try more variation.
Happy Learning !!
Comments