Java Regex to check Min/Max Length of Input Text

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 !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode